Android - A card item in gridview is repeated twice - java

ListAdapter.java
public class ListAdapter extends ArrayAdapter<String>
{
private Activity context;
private int[] icon;
private String[] title;
public ListAdapter(Activity context, int[] icon, String[] title)
{
super(context, R.layout.list_item, title);
this.context = context;
this.icon = icon;
this.title = title;
}
public View getView(final int position, View view, final ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_item, null, true);
try
{
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtTitle);
ImageView imgIcon = (ImageView) rowView.findViewById(R.id.imgIcon);
txtTitle.setText(title[position]);
imgIcon.setBackgroundResource(icon[position]);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
return rowView;
}
}}
MainActivity.java
In this card Events is replaced with Services. When I re-shuffle the positions the changes are reflected in the app but when I run the app again the Gallery is replaced by Services.
public class MainActivity extends AppCompatActivity
{
String[] title = {
"Services" ,
"Solutions",
"Customers",
"Events",
"Gallery",
"Contact Us"
};
int[] icon = {
R.drawable.services_icon,
R.drawable.solution_icon,
R.drawable.customer_icon,
R.drawable.event_icon,
R.drawable.gallery_icon,
R.drawable.contact_us_icon
};
HomeGrid adapter = new HomeGrid(MainActivity.this, title, icon, back);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (title[position]) {
case "Services":
Intent i1 = new Intent(MainActivity.this, Listing.class);
startActivity(i1);
break;
case "Solutions":
//Intent i2 = new Intent(MainActivity.this, Listing.class);
//startActivity(i2);
Toast.makeText(MainActivity.this, "You Clicked at " + title[position], Toast.LENGTH_SHORT).show();
break;
case "Customers":
Toast.makeText(MainActivity.this, "You Clicked at " + title[position], Toast.LENGTH_SHORT).show();
break;
case "Gallery":
Toast.makeText(MainActivity.this, "You Clicked at " + title[position], Toast.LENGTH_SHORT).show();
break;
case "Events":
Intent i3 = new Intent(MainActivity.this, Form.class);
startActivity(i3);
break;
case "Contact Us":
Toast.makeText(MainActivity.this, "You Clicked at " + title[position], Toast.LENGTH_SHORT).show();
break;
}
}
});
}

Use this.
public class ListAdapter extends ArrayAdapter<String>{
private Activity context;
private int[] icon;
private String[] title;
private LayoutInflater inflater;
public ListAdapter(Activity context, int[] icon, String[] title)
{
super(context, R.layout.list_item, title);
this.context = context;
this.icon = icon;
this.title = title;
inflater = LayoutInflater.from(context);
}
public View getView(final int position, View view, final ViewGroup parent)
{
view= inflater.inflate(R.layout.list_item, parent, false);
try
{
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
ImageView imgIcon = (ImageView) view.findViewById(R.id.imgIcon);
txtTitle.setText(title[position]);
imgIcon.setBackgroundResource(icon[position]);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
return view;
}
}
}

Related

Android gridview image The application may be doing too much work on its main thread

I am using a alert dialog to display images from file. But when i press the button to show alert dialog the app freezes fro 6 seconds and then the alert dialog will come...
My code...
listView_prev.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, final View arg1, int arg2, long arg3) {
//listview click event handling
TextView id = (TextView) arg1.findViewById(R.id.textView17);
final int id_To_Search = Integer.valueOf(id.getText().toString());
Cursor item=mydb.singlecons(id_To_Search);
Cursor att=mydb.attrs(id_To_Search);
Cursor picloc=mydb.singleconspic(id_To_Search);
att.moveToFirst();
List<String> list = new ArrayList<>();
// Log.d("temp",att.getColumnName(1));
while (!att.isAfterLast())
{
int l=att.getColumnCount();
Log.d("length", String.valueOf(l));
for(int i=2;i<l;i++){
Log.d("for","for");
if(att.getString(i)!=null){
String b= att.getColumnName(i)+" "+att.getString(i);
list.add(b);
Log.d("att",b);
}
}
Log.d("while","while");
att.moveToNext();
}
att.close();
Log.d("list", String.valueOf(list));
picloc.moveToFirst();
FilePathStrings = new String[picloc.getCount()];
int i=0;
while (!picloc.isAfterLast()){
Log.d("picloc",picloc.getString(2));
FilePathStrings[i]=picloc.getString(2);
i++;
picloc.moveToNext();
}
item.moveToFirst();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Consultation.this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
TextView con=(TextView)dialogView.findViewById(R.id.textView29);
con.setText("Consultation on "+item.getString(4));
TextView des=(TextView)dialogView.findViewById(R.id.textView28);
des.setText(item.getString(2));
TextView pre=(TextView)dialogView.findViewById(R.id.textView31);
pre.setText(item.getString(3));
TextView fee=(TextView)dialogView.findViewById(R.id.textView32);
fee.setText(item.getString(5));
adapter1 = new GridViewAdapter(FilePathStrings,getApplicationContext());
grid = (GridView) dialogView.findViewById(R.id.gridview);
grid.setAdapter(adapter1);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + FilePathStrings[position]), "image/*");
startActivity(intent);
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
Gridviewadapter.java
class GridViewAdapter extends BaseAdapter {
private String[] filepath;
private static LayoutInflater inflater = null;
GridViewAdapter(String[] fpath,Context context) {
filepath = fpath;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return filepath.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.gridview_item, null);
ImageView image = (ImageView) vi.findViewById(R.id.image);
Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);
Bitmap thumbBitmap = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(filepath[position]),320,240);
image.setImageBitmap(thumbBitmap);
return vi;
}
}
How can i resolve this issue.? I know asyctask will help... How can i resolve this
use handler ,
handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
alertDialog.show();
}
});
I think for best performance is to do this in another activity
anyway,if not, use AsyncTask class, example:
listView_prev.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, final View arg1, int arg2, long arg3) {
//listview click event handling
TextView id = (TextView) arg1.findViewById(R.id.textView17);
final int id_To_Search = Integer.valueOf(id.getText().toString());
new displaysImages().execute(id_To_Search);
}});
....
class displaysImages extends AsyncTask<Integer, Void, Void> {
ProgressDialog dialog;
Cursor item=null;
String FilePathStrings[];
#Override
protected void onPreExecute() {
super.onPreExecute();
/* show ProgressDialog before doing anything*/
dialog = ProgressDialog.show(getApplicationContext(), "Veuillez patienter", "Chargement des données....", true);
}
#Override
protected Void doInBackground(Integer... param) {
try {
item=mydb.singlecons(param[0]);
Cursor att=mydb.attrs(param[0]);
Cursor picloc=mydb.singleconspic(param[0]);
att.moveToFirst();
List<String> list = new ArrayList<>();
// Log.d("temp",att.getColumnName(1));
while (!att.isAfterLast())
{
int l=att.getColumnCount();
Log.d("length", String.valueOf(l));
for(int i=2;i<l;i++){
Log.d("for","for");
if(att.getString(i)!=null){
String b= att.getColumnName(i)+" "+att.getString(i);
list.add(b);
Log.d("att",b);
}
}
Log.d("while","while");
att.moveToNext();
}
att.close();
Log.d("list", String.valueOf(list));
picloc.moveToFirst();
FilePathStrings = new String[picloc.getCount()];
int i=0;
while (!picloc.isAfterLast()){
Log.d("picloc",picloc.getString(2));
FilePathStrings[i]=picloc.getString(2);
i++;
picloc.moveToNext();
}
item.moveToFirst();
} catch (Exception e) {
e.printStackTrace();
dialog.dismiss();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Consultation.this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
TextView con=(TextView)dialogView.findViewById(R.id.textView29);
con.setText("Consultation on "+item.getString(4));
TextView des=(TextView)dialogView.findViewById(R.id.textView28);
des.setText(item.getString(2));
TextView pre=(TextView)dialogView.findViewById(R.id.textView31);
pre.setText(item.getString(3));
TextView fee=(TextView)dialogView.findViewById(R.id.textView32);
fee.setText(item.getString(5));
adapter1 = new GridViewAdapter(FilePathStrings,getApplicationContext());
grid = (GridView) dialogView.findViewById(R.id.gridview);
grid.setAdapter(adapter1);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + FilePathStrings[position]), "image/*");
startActivity(intent);
}
});
AlertDialog alertDialog = dialogBuilder.create();
dialog.dismiss();
alertDialog.show();
}}
i didn't test the code, but i think it work like that

Create Cache listview of my data populated from the server

I want to create a cache that stores present listview populated from the server which means even if users are not online they can have access to the listview data been loaded before going offline. These are my codes that contains the swipelistlayout and the main class Tab4
public class Tab4 extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener {
private int index;
ImageSwitcher switcher;
android.os.Handler Handler = new android.os.Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
private String URL_TOP_250 = "http://172.126.43.152/locator/test/refractor2.php?offset=";
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.tab_4,container,false);
listView = (ListView) vi.findViewById(R.id.list4);
listView.setBackgroundColor(Color.WHITE);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) vi.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
//getView().setOnClickListener();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
return vi;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent();
intent.setClass(getActivity(), Newbies.class);
//String text = String.valueOf(movieList.get(position));
String text = movieList.get(position).getSlug();
//Toast.makeText(getActivity().getApplicationContext(), text, Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(), Newbies.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
// Movie m = new Movie();
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
String author = movieObj.getString("postAuthor");
String slug = movieObj.getString("postSlug");
String categories = "technologies";
String thumbnailUrl = movieObj.getString("postPic");
String year = movieObj.getString("postDate");
Movie m = new Movie(rank, title, author, slug, categories, thumbnailUrl, year);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
And the SwipeListAdapter class is below...
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView author = (TextView) convertView.findViewById(R.id.author);
//String slug;
TextView category = (TextView) convertView.findViewById(R.id.category);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieList.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
author.setText(m.getAuthor());
// slug.setText(m.getAuthor());
category.setText(m.getCategories());
// release year
year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
Any help will be appreciated. Thanks.

Get parent layout from custom Adapter

Could anybody explain me, how to realize?
I have an activity with listview and footer with some elements(textview).
Listview built with custom adapter. Each listview item has few elements. And my question: how can i change textview in footer, from custom adapter, when i clicking on some listview's element?
Thx a lot!
/**** My adapter ****/
public class MyListAdapter extends ArrayAdapter<Product> implements UndoAdapter {
private final Context mContext;
private HashMap<Product, Integer> mIdMap = new HashMap<Product, Integer>();
ArrayList<Product> products = new ArrayList<Product>();
final int INVALID_ID = -1;
LayoutInflater lInflater;
String imagePath;
public MyListAdapter(Context context, int textViewResourceId, List<Product> prod) {
//super(context, textViewResourceId, prod);
super(prod);
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
for (int i = 0; i < prod.size(); i++) {
//add(prod.get(i));
mIdMap.put(prod.get(i),i);
}
}
#Override
public long getItemId(final int position) {
//return getItem(position).hashCode();
Product item = (Product) getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;;
Product p = getItem(position);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.item, null);
//convertView.setBackgroundResource(R.drawable.rounded_corners);
int currentTheme = Utils.getCurrentTheme(convertView.getContext());
switch (currentTheme) {
case 0:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
case 1:
convertView.setBackgroundResource(R.drawable.border);
break;
default:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
}
holder = new ViewHolder();
holder.tvDescr = (TextView) convertView.findViewById(R.id.tvDescr);
holder.list_image = (ImageView) convertView.findViewById(R.id.list_image);
holder.products_amount = (TextView) convertView.findViewById(R.id.amountDigits);
holder.products_price = (TextView) convertView.findViewById(R.id.priceDigits);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
holder.unit = (TextView) convertView.findViewById(R.id.unit);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(p.getProductImageBitmap() != null && p.getProductImageBitmap() != "") {
Log.d("PATH -- ", p.getProductImageBitmap());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
/*.showImageOnLoading(R.id.progress_circular)*/
.build();
imageLoader.displayImage(p.getProductImageBitmap(), holder.list_image, options);
} else {
holder.list_image.setImageResource(R.drawable.ic_launcher);
}
holder.tvDescr.setText(p.getProductName());
holder.ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String deletedItem = getItem(position).getProductName();
MyListAdapter.this.remove(getItem(position));
if (MyListAdapter.this.getCount() > 0) {
Toast.makeText(mContext, deletedItem + " " + mContext.getString(R.string.deleted_item), Toast.LENGTH_SHORT).show();
MyListAdapter.this.notifyDataSetChanged();
} else {
Toast.makeText(mContext,mContext.getString(R.string.sklerolist_empty), Toast.LENGTH_SHORT).show();
}
}
});
//Функционал для большой картинки продукта
//открывается новое активити с большой картинкой
holder.list_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePath = getItem(position).getProductImageBitmap();
if(imagePath != null && imagePath != "") {
Pattern normalPrice = Pattern.compile("^file");
Matcher m2 = normalPrice.matcher(imagePath);
if (m2.find()) {
Intent myIntent = new Intent(view.getContext(), ViewImage.class).putExtra("imagePath", imagePath);
view.getContext().startActivity(myIntent);
}
}
}
});
holder.products_price.setText(fmt(p.getProductPrice()));
holder.products_amount.setText(fmt(p.getProductAmount()));
holder.unit.setText(p.getProductUnit());
return convertView;
}
public static String fmt(double d){
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
static class ViewHolder {
ImageView list_image;
TextView tvDescr;
TextView products_amount;
TextView products_price;
TextView unit;
ImageView ivImage;
ProgressBar circleProgress;
}
#NonNull
#Override
public View getUndoView(final int position, final View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
if (view == null) {
//view = LayoutInflater.from(mContext).inflate(R.layout.undo_row, parent, false);
view = lInflater.inflate(R.layout.undo_row, parent, false);
}
return view;
}
#NonNull
#Override
public View getUndoClickView(#NonNull final View view) {
return view.findViewById(R.id.undo_row_undobutton);
}
public View getHeaderView(final int position, final View convertView, final ViewGroup parent) {
TextView view = (TextView) convertView;
//View view = convertView;
if (view == null) {
//view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.list_header, parent, false);
//view = lInflater.inflate(R.layout.list_header, parent, false);
}
//view.setText(mContext.getString(R.string.header, getHeaderId(position)));
return view;
}
public long getHeaderId(final int position) {
return position / 10;
}
}
Your ListView has a listener for the click events on list elements.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something when a list item is clicked
}
But if you want to pas something else back from the adapter to the Activity or the Fragment that contains that ListView and Adapter, you should create a simple interface and set it as listener to your adapter. After that, set click events on your rows from within the adapter, and notify the Activity or Fragment using your own interface.
For example you have the interface defined like this
public interface OnItemClickedCustomAdapter {
public void onClick(ItemPosition position);
}
and in your Adapter class you will have a private member
private OnItemClickedCustomAdapter mListener;
and a method used to set the listener
public void setOnItemClickedCustomAdapter(OnItemClickedCustomAdapter listener){
this.mListener = listener;
}
From your Activity or Fragment where your ListView is defined, and your adapter is set, you will be able to call setOnItemClickedCustomAdapter with this as parameter, and there you go. Your activity will now listen for your events. To trigger an event, just call mListener.onClick() from your custom adapter. You can pass back data you need back to the Activity or Fragment, and from there you have access to your Header or Footer directly, and you can change the text on them.

Android FLAG_ACTIVITY_NEW_TASK not working

I'm having an issue with calling startActivity() on an Intent from within my custom onClick Listener. The code compiles fine, but when it gets to that point in the execution, I get a nullPointerException.
Code
private static class ProverbAdapter extends ArrayAdapter<String> {
MainActivity ma;
public ProverbAdapter(Context context, int layout, int resId, String[] items) {
super(context, layout, resId, items);
this.ma = new MainActivity();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
Context context = getContext();
if(row == null) {
row = LayoutInflater.from(context).inflate(R.layout.proverb_layout, parent, false);
}
String item = getItem(position);
TextView proverbDate = (TextView)row.findViewById(R.id.proverb_date);
TextView proverbText = (TextView)row.findViewById(R.id.proverb_content);
String[] data = item.split("----");
proverbDate.setText(data[0]);
proverbText.setText(data[1]);
ImageButton emailButton = (ImageButton)row.findViewById(R.id.emailButton);
ImageButton twitterButton = (ImageButton)row.findViewById(R.id.twitterButton);
ImageButton facebookButton = (ImageButton)row.findViewById(R.id.facebookButton);
emailButton.setOnClickListener(this.ma.new ProverbOnClickListener(data[0], data[1], "email", context));
twitterButton.setOnClickListener(this.ma.new ProverbOnClickListener(data[0], data[1], "twitter", context));
facebookButton.setOnClickListener(this.ma.new ProverbOnClickListener(data[0], data[1], "facebook", context));
return row;
}
}
public class ProverbOnClickListener implements OnClickListener {
String proverb_date, proverb_content, eventType;
Context context;
public ProverbOnClickListener(String proverb_date, String proverb_content, String eventType, Context context) {
this.proverb_date = proverb_date;
this.proverb_content = proverb_content;
this.eventType = eventType;
this.context = context;
}
#Override
public void onClick(View v) {
Toast.makeText(this.context, this.eventType + ": " + this.proverb_content, Toast.LENGTH_SHORT).show();
if(this.eventType == "email") {
Intent i = new Intent(Intent.ACTION_SEND);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
context.startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this.context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
}
Exception
FATAL EXCEPTION: main android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
I added the new flag as the compiler suggested, but it still crashes with the same error.
* *EDIT ****
After following advice in the first response, my adapter now looks like:
private static class ProverbAdapter extends ArrayAdapter<String> {
Context context;
public ProverbAdapter(Context context, int layout, int resId, String[] items) {
super(context, layout, resId, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.proverb_layout, parent, false);
}
String item = getItem(position);
TextView proverbDate = (TextView)row.findViewById(R.id.proverb_date);
TextView proverbText = (TextView)row.findViewById(R.id.proverb_content);
String[] data = item.split("----");
proverbDate.setText(data[0]);
proverbText.setText(data[1]);
ImageButton emailButton = (ImageButton)row.findViewById(R.id.emailButton);
ImageButton twitterButton = (ImageButton)row.findViewById(R.id.twitterButton);
ImageButton facebookButton = (ImageButton)row.findViewById(R.id.facebookButton);
emailButton.setOnClickListener(new ProverbOnClickListener(data[0], data[1], "email", context));
twitterButton.setOnClickListener(new ProverbOnClickListener(data[0], data[1], "twitter", context));
facebookButton.setOnClickListener(new ProverbOnClickListener(data[0], data[1], "facebook", context));
return row;
}
}
However I'm receiving a compilation error.
No enclosing instance type of MainActivity is accessible.
Try Few modifications
this.ma = new MainActivity(); //it is wrong
Don't instantiate Activity
try like this
Context context;
public ProverbAdapter(Context context, int layout, int resId, String[] items) {
super(context, layout, resId, items);
this.context=context;
}
use this variable context where ever you need context

How to dissmiss AlertDialog from ArrayAdapter

I created singe choice AlertDialog with radio buttons using ArrayAdapter. It's possible to dissmiss that alert dialog when Ratio is selected? I have OnClick listener in ArrayAdapter class holder.name.setOnClickListener, but i have no idea how to to that.
AlertDialog code:
Builder builder = new Builder(serveris, useris, paswordas, BuildBuildingsViewActivity.this, USER_AGENT);
ArrayList<AvailableBuildings> availableBuildings = builder.checkForPossibleBuildings(pastatas.getBuildingLink());
ArrayAdapter<AvailableBuildings> adapter = new AvailableBuildingsAdapter(BuildBuildingsViewActivity.this, R.layout.choice_main, availableBuildings, host, curdid, pastatas.getBuildingLink());
new AlertDialog.Builder(BuildBuildingsViewActivity.this)
.setSingleChoiceItems(adapter, 0, null)
.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
ArrayAdapter code:
public class AvailableBuildingsAdapter extends ArrayAdapter<AvailableBuildings> {
public DBAdapterBuild db_build;
public AvailableBuildingsAdapter(Context context, int textViewResourceId,ArrayList<AvailableBuildings> availableBuildings, String host, String curdid, String aiksteles_link) {
super(context, textViewResourceId, availableBuildings);
this.context = context;
this.availableBuildings = new ArrayList<AvailableBuildings>();
this.availableBuildings.addAll(availableBuildings);
this.host = host;
this.curdid = curdid;
this.aiksteles_link = aiksteles_link;
db_build = new DBAdapterBuild(context, host);
}
private String host;
private Context context;
private String curdid;
private String aiksteles_link;
private ArrayList<AvailableBuildings> availableBuildings;
static class ViewHolder {
RadioButton name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.choice_row, null);
holder = new ViewHolder();
holder.name = (RadioButton) convertView.findViewById(R.id.building_name);
convertView.setTag( holder );
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
db_build.open();
RadioButton name = (RadioButton) v;
AvailableBuildings building = (AvailableBuildings) name.getTag();
Log.e( "Available: ", ""+building.getAvailable_title()+building.getAvailable_code());
Log.e( "Available: ", ""+db_build.insertTitle(1, building.getAvailable_title(), aiksteles_link, curdid, 0, 1, building.getAvailable_type(), "3", building.getAvailable_code()));
db_build.close();
}
});
} else {
// view already defined, retrieve view holder
holder = (ViewHolder) convertView.getTag();
}
AvailableBuildings building = availableBuildings.get(position);
if ( building == null ) {
}
holder.name.setText(building.getAvailable_title());
holder.name.setTag(building);
return convertView;
}
}
I solve this problem passing to ArrayAdapter constructor Dialog object and next doing like this:
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
db_build.open();
RadioButton name = (RadioButton) v;
AvailableBuildings building = (AvailableBuildings) name.getTag();
Log.e( "Available: ", ""+building.getAvailable_title()+building.getAvailable_code());
Log.e( "Available: ", ""+db_build.insertTitle(1, building.getAvailable_title(), aiksteles_link, curdid, 0, 1, building.getAvailable_type(), "3", building.getAvailable_code()));
db_build.close();
dia.dismiss();
}
});

Categories

Resources