Pass current item position to inner class? - java

How can I pass the current Hashmap key position to my inner class?
I need to pass data.get(position) to my inner class Click. Normally I would declare it final, but I'm not seeing how this is done in this case?
public class UpcomingGridViewAdapter extends BaseAdapter {
public boolean pressedMovieItem;
Context context;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> mylist = new HashMap<>();
public UpcomingGridViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.upcoming_grid_item, parent, false);
}
final ImageView poster = (ImageView) convertView.findViewById(R.id.upcoming_image);
mylist = data.get(position);
final String posterPath = mylist.get("poster_path");
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
final String url = "http://image.tmdb.org/t/p/w185" + posterPath;
// load image url into poster
Picasso.with(context).load(url).into(poster);
// load image url into poster
// Get onclick of item and pass data to singleitemview for upcoming
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// need to pass data.get(position) to the inner class click
new Click().execute();
}
});
return convertView;
}
// Downloading data asynchronously
class Click extends AsyncTask< Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO setup progressdialog
}
#Override
protected Void doInBackground(Void... params) {
mylist = data.get(position); // need to get position
Intent intent = new Intent(context, UpcomingSingleItem.class);
intent.putExtra("poster_path", mylist.get(Upcoming.TAG_POSTER));
intent.putExtra("title", mylist.get(Upcoming.TAG_TITLE));
intent.putExtra("release_date", mylist.get(Upcoming.TAG_RELEASE));
intent.putExtra("overview", mylist.get(Upcoming.TAG_OVERVIEW));
intent.putExtra("id", mylist.get(Upcoming.TAG_ID));
intent.putExtra("vote_average", mylist.get(Upcoming.TAG_VOTE_AVG));
context.startActivity(intent);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// TODO stop progressdialog
}
}
}

I think you want position in your Click asynctask for that pass your position in asynctask call :
new Click().execute(position);
Then receive it using params like this :
mylist = data.get(params[0]); // get position here which is passed

If i get you right you only need to execute your AsyncTask with params. See the documentation:
http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...)

Related

RecyclerView Adapter Error

MainFragment:
public class MainFragment extends Fragment {
RecyclerView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
// URL Address
String url = "http:";
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String x = "/aaa/bbb/omer/000";
String []tokens = x.split("/aaa/bbb/");
for (String t: tokens)
Toast.makeText(getActivity(), t, Toast.LENGTH_SHORT).show();
View view =inflater.inflate(R.layout.fragment_main, container, false);
listview = (RecyclerView) view.findViewById(R.id.listview);
listview.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
listview.setLayoutManager(llm);
new JsoupListView().execute();
return view;
}
// Title AsyncTask
private class JsoupListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Diziler Yükleniyor");
// Set progressdialog message
mProgressDialog.setMessage("Yükleniyor...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Connect to the Website URL
Document doc = Jsoup.connect(url).get();
// Identify Table Class "worldpopulation"
for (Element table : doc.select("div[class=col-sm-12 col-xs-12 pad0 middle]")) {
// Identify all the table row's(tr)
for (Element row : table.select("div[class=col-sm-12 col-xs-12 pad0 streamingBoxWrap mNewsItem]:gt(0)")) {
HashMap<String, String> map = new HashMap<String, String>();
// Identify all the table cell's(td)
Elements tds = row.select("a");
// Identify all img src's
Elements imgSrc = row.select("img[src]");
// Get only src from img src
String imgSrcStr = imgSrc.attr("src");
Elements aSrc = row.select("a[href]:gt(1)");
String aSrcStr = aSrc.attr("href");
// Retrive Jsoup Elements
// Get the first td
map.put("rank", aSrcStr);
// Get the second td
map.put("country", tds.get(1).text());
// Get the third td
map.put("population", tds.get(2).text());
// Get the image src links
map.put("flag", imgSrcStr);
// Set all extracted Jsoup Elements into the array
arraylist.add(map);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
listview.setAdapter(adapter);
listview.setItemAnimator(new DefaultItemAnimator());
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
ListViewAdapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
final TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.singleitemview, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainFragment.RANK));
country.setText(resultp.get(MainFragment.COUNTRY));
population.setText(resultp.get(MainFragment.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainFragment.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
DiziFragment myFragment3 = new DiziFragment();
Bundle bundle = new Bundle();
bundle.putString("gun",resultp.get(MainFragment.POPULATION));
bundle.putString("flag",resultp.get(MainFragment.FLAG));
myFragment3.setArguments(bundle);
android.support.v4.app.FragmentTransaction fragmentTransaction = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,myFragment3);
fragmentTransaction.commit();
}
});
return itemView;
}
}
Gradle build
I want to list items with recyclerview. Help me Please.
Turkish:kodda listview ile liteliyordu ben ise recyclerview ile listelemek istiyorum.
edit my code
adapter:
public class SimpleRecyclerAdapter extends RecyclerView.Adapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public SimpleRecyclerAdapter(Context context,ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int position) {
final TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.singleitemview, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainFragment.RANK));
country.setText(resultp.get(MainFragment.COUNTRY));
population.setText(resultp.get(MainFragment.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainFragment.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
DiziFragment myFragment3 = new DiziFragment();
Bundle bundle = new Bundle();
bundle.putString("gun",resultp.get(MainFragment.POPULATION));
bundle.putString("flag",resultp.get(MainFragment.FLAG));
myFragment3.setArguments(bundle);
android.support.v4.app.FragmentTransaction fragmentTransaction = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,myFragment3);
fragmentTransaction.commit();
}
});
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
return itemView; is eroor
If you are using recycler view then your adapter should also extends recycler view instead of Base Adapter. For eg.
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeedItem feedItem = feedItemList.get(i);
//Download image using picasso library
Picasso.with(mContext).load(feedItem.getThumbnail())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle()));
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}

Android : Update data-set where data-set is ArrayList of HashMaps

I recently started working on an Android project and given my lack of understanding of UI programming, I find myself in a fix, when I try to dynamically add a entry to the UI.
I am working on a chat-application in which when a new message is received, it should be added at the bottom. For that I need to notify that the data-set has changed. When I was directly calling data-set has changed, I was getting an error. So I used a local broadcast reciever on the adapter.
Unfortunately, I don't know how to pass the ArrayList which contains a HashMap. I will post the code of the adapter and where I am trying to notify where data has changed. I hope someone can help me out. THanks a lot.. :-)
Code :
public static void recieveUpdatedMessage(String channelName, Map<String, Object> input){
//The input here contains message from our PUSH system
Intent intent = new Intent();
HashMap<String, String> insertMap = new HashMap<>();
insertMap.put(chatText, String.valueOf(input.get("text")));
insertMap.put(firstName,String.valueOf("firstname"));
insertMap.put(groupChannel, "/service/chat" + String.valueOf(groupAccountId));
ArrayList<HashMap<String, String>> chatMessagesHashMapList = new ArrayList<HashMap<String, String>>();
chatMessagesHashMapList.add(insertMap);
// Below is where I am trying to send data.
// intent.putExtra(chatMessagesHashMapList);//send any data to your adapter
intent.setAction("myaction");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
The adapter code, it's in same java file :
public class ChatMessagesAdapter extends BaseAdapter {
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals("MYREFRESH"))
{
notifyDataSetChanged();
}
}
};
private Activity activity = null;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
public ChatMessagesAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("MYREFRESH");
LocalBroadcastManager.getInstance(context).registerReceiver(broadcastReceiver, intentFilter);
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#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.chat_messages_row, parent, false);
TextView chatText = (TextView) vi.findViewById(R.id.chatText);
ImageView userImage = (ImageView) vi.findViewById(R.id.chatImage);
TextView firstName = (TextView) vi.findViewById(R.id.personName);
HashMap<String, String> chatList = new HashMap<>();
chatList = data.get(position);
chatText.setText(chatList.get(ChatMessagesActivity.chatText));
userImage.setImageBitmap(convertByteArrayToBitmap(chatList.get(ChatMessagesActivity.chatImage)));
firstName.setText(chatList.get(ChatMessagesActivity.firstName));
return vi;
}
}
I hope I was clear. If there is anything missing, kindly let me know. How can I tell the activity that there is a new message and put it at the bottom.
You really should not use a BroadcastReceiver that way. Try adding an add method to the Adapter to make it easier to add an item and automatically notify a change.
public void add(HashMap<String, String> item) {
data.add(item);
notifyDataSetChanged();
}
Then in the recieveUpdatedMessage method you can do something similar to the following.
public void recieveUpdatedMessage(String channelName, Map<String, Object> input) {
HashMap<String, String> insertMap = new HashMap<>();
insertMap.put(chatText, input.get("text").toString());
insertMap.put(firstName, input.get("firstname").toString());
insertMap.put(groupChannel, "/service/chat" + input.get("groupaccountid").toString());
myAdapter.add(insertMap);
}
A few notes for improvement
Instead of using a HashMap it would be better to create a class to hold the data for you.
Since your BaseAdapter is already using a List you could extend an ArrayAdapter instead since that already has an add method that also calls notifyDataSetChanged() by default.
You can pass latest data in your case you are creating data with HashMap directly into intent using bundle. & retrive it from the onReceive method of BroadCastReceiver
How to Pass data check your updated method recieveUpdatedMessage below
recieveUpdatedMessage
public static void recieveUpdatedMessage(String channelName, Map<String, Object> input) {
//The input here contains message from our PUSH system
Intent intent = new Intent();
HashMap<String, String> insertMap = new HashMap<>();
insertMap.put(chatText, String.valueOf(input.get("text")));
insertMap.put(firstName, String.valueOf("firstname"));
insertMap.put(groupChannel, "/service/chat" + String.valueOf(groupAccountId));
ArrayList<HashMap<String, String>> chatMessagesHashMapList = new ArrayList<HashMap<String, String>>();
// Added your map into Bundler as a Serializable
Bundle bundle = new Bundle();
bundle.putSerializable("chatMapKey", insertMap);
// after adding map into bundle . bundle is added into Intent
intent.putExtras(bundle);
// Below is where I am trying to send data.
// intent.putExtra(chatMessagesHashMapList);//send any data to your adapter
intent.setAction("MYREFRESH");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
How to retrive data from bundle & update it in listview check your ChatMessagesAdapter updated code.
ChatMessagesAdapter
public class ChatMessagesAdapter extends BaseAdapter {
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("MYREFRESH")) {
Bundle bundle = intent.getExtras();
// Get the bundle from intent
if (bundle!=null && bundle.containsKey("chatMapKey")) {
// get the Serializable object which is pass as a broadcast from the Bundle
refreshChat((HashMap<String, String>) bundle.getSerializable("chatMapKey"));
}
}
}
};
private Activity activity = null;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
private int size = 0;
public ChatMessagesAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("MYREFRESH");
LocalBroadcastManager.getInstance(context).registerReceiver(broadcastReceiver, intentFilter);
activity = a;
data = d;
if (data != null)
size = data.size();
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void refreshChat(HashMap<String, String> newChatMap) {
if (data == null) {// Added Condition for safe side you can remove it
data = new ArrayList<HashMap<String, String>>();
}
data.add(newChatMap);
size = data.size();
notifyDataSetChanged();
}
#Override
public int getCount() {
return size;
}
#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.chat_messages_row, parent, false);
TextView chatText = (TextView) vi.findViewById(R.id.chatText);
ImageView userImage = (ImageView) vi.findViewById(R.id.chatImage);
TextView firstName = (TextView) vi.findViewById(R.id.personName);
HashMap<String, String> chatList = new HashMap<>();
chatList = data.get(position);
chatText.setText(chatList.get(ChatMessagesActivity.chatText));
userImage.setImageBitmap(convertByteArrayToBitmap(chatList.get(ChatMessagesActivity.chatImage)));
firstName.setText(chatList.get(ChatMessagesActivity.firstName));
return vi;
}
}
Suggestions
Avoid using Broadcast reciver like you have used. Register it in
Activity onReusme/onStart & Unregister it in its onPause/onStop
method check this The visible lifetime
Try to maintain data with database like at the time of message
receive insert it in database & at the time of refreshing data get
the data from database

from simple list adapter to custom array adapter

I have a class which retrives data from my database and displays it in a listview using simple adapter
public class ViewExs extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://www.lamia.byethost18.com/get_all_ex.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "ID_exercise";
private static final String TAG_NAME = "ID_exercise";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_exs);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), EditProductActivity.class);
startActivity(i);
/* // getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);*/
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewExs.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewExs.this, productsList,
R.layout.item_list_3, new String[] {TAG_NAME},
new int[] { R.id.pid});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
i want to use a custom adapter rather than the simple adapter .. here is my custom adapter
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
TextView textView;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.item_list_3, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item_list_3, parent, false);
final TextView textView = (TextView) rowView.findViewById(R.id.pid);
textView.setText(values[position]);
return rowView;
}
}
how i do this part of code
ListAdapter adapter = new SimpleAdapter(
ViewExs.this, productsList,
R.layout.item_list_3, new String[] {TAG_NAME},
new int[] { R.id.pid});
// updating listview
setListAdapter(adapter);
in the custom adapter ?
can someone help please ?
Just use the MySimpleArrayAdapter in your method and set the adapter -
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable()
{
public void run()
{
/**
* Updating parsed JSON data into ListView
* */
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(ViewExs.this,
new String[] {TAG_NAME});
// updating listview
setListAdapter(adapter);
}
});
}
Suppose your arrays of values is String[] values, then
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(
ViewExs.this,values);
setListAdapter(adapter);
Hi I used a custom array adapter like the one below, it's just a sample. But I hope it helps. It displays data that was sent to it using an ArrayList from an fragment where it is displayed.
public class MovieAdapter extends ArrayAdapter<Movie> {
private Context context;
private List<Movie> movies;
public MovieAdapter(Context context, List<Movie> movies) {
super(context, R.layout.movie_layout, movies);
this.context = context;
this.movies = movies;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View movieView = convertView;
if (movieView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
movieView = inflater.inflate(R.layout.movie_layout, parent, false);
}
movieView.setTag(movies.get(position));
TextView txtTitle = (TextView) movieView.findViewById(R.id.txtTitle);
TextView txtDate = (TextView) movieView.findViewById(R.id.txtDate);
RatingBar ratingBar = (RatingBar) movieView
.findViewById(R.id.ratingBar);
txtTitle.setText(movies.get(position).MovieTitle);
txtDate.setText("Date Viewed: " + movies.get(position).dateViewed);
ratingBar.setIsIndicator(true);
ratingBar.setNumStars(movies.get(position).rating);
ratingBar.setRating(movies.get(position).rating);
return movieView;
}
}
The fragment
public class MyListFragment extends Fragment {
Movie movie;
MovieAdapter adapter;
MovieSelectedListener callBack;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
ListView movieList = (ListView) view.findViewById(R.id.movieList);
movieList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView movie = (TextView) view.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onMovieSelected(title);
}
});
if (getArguments() != null)
movie = (Movie) getArguments().getSerializable("Movie");
Log.v("PASSED", "Got here");
adapter = new MovieAdapter(getActivity(), movie.movies);
movieList.setAdapter(adapter);
movieList.setLongClickable(true);
movieList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent,
final View view, int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder dialog = new AlertDialog.Builder(
getActivity());
dialog.setMessage("Are you sure you want to delete this movie?");
dialog.setTitle("Alert Message");
dialog.setCancelable(false);
dialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
TextView movie = (TextView) view
.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onDeleteSelected(title, adapter);
}
});
dialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
});
dialog.show();
return false;
}
});
return view;
}
public interface MovieSelectedListener {
public void onMovieSelected(String movie);
public void onDeleteSelected(String movie, MovieAdapter adapter);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
;
try {
callBack = (MovieSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement MovieSelectedListener");
}
}
public void sortTitle() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.MovieTitle.compareTo(rhs.MovieTitle);
}
});
adapter.notifyDataSetChanged();
}
public void sortDateViewed() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.dateViewed.compareTo(rhs.dateViewed);
}
});
adapter.notifyDataSetChanged();
}
public void sortRating() {
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return ((Integer) lhs.rating).compareTo(rhs.rating);
}
});
adapter.notifyDataSetChanged();
}
}

ListView doesn't show refreshed content

I have a custom adapter which extends from BaseAdapter..
Custom adapter code :
public class SearchListViewAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private JsonArray searchResults;
public SearchListViewAdapter(Context context, JsonArray searchResults) {
this.searchResults = searchResults;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return searchResults.count();
}
#Override
public Object getItem(int position) {
return searchResults.get(position);
}
/*public ListAdapter updateResults(JsonArray results) {
searchResults = results;
notifyDataSetChanged();
return null;
}*/
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
JsonObject searchResult = (JsonObject)getItem (position);
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.custom_search_result, null);
holder = new ViewHolder();
holder.txtFullName = (TextView) convertView.findViewById(R.id.FullName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtFullName.setText(searchResult.getString ("FirstName") + searchResult.getString ("LastName"));
return convertView;
}
static class ViewHolder {
TextView txtFullName;
}
}
Activity code :
// After displaying the list in an onPostExecute Method of an AsyncTask class
// I call another async task : BarcodeAction by giving the param : records
new BarcodeAction(records).execute("");
private class BarcodeAction extends AsyncTask<String, Void, JsonArray> {
private JsonArray records;
public BarcodeAction(JsonArray result)
{
this.records = result;
}
#Override
protected JsonArray doInBackground(String... params) {
// Processing... if it's success the onPostExecute method receive : records
if (resultType.equals("success"))
return records;
return null;
}
#Override
protected void onPostExecute(final JsonArray records) {
final ListView lv1 = (ListView) findViewById(R.id.ListViewSearchResults);
// EDIT : notifyDataSetChange doesn't work
SearchListViewAdapter svla1 = new SearchListViewAdapter(SearchActivity.this, records);
lv1.setAdapter(svla1);
svla1.notifyDataSetChanged();
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
JsonObject response = (JsonObject)o;
SearchActivity.VISITOR_BARCODE = response.getString("Barcode");
new BarcodeAction(records).execute("");
}
});
}
}
But my list is not getting refreshed..
Do you have any idea about this ? Thnak you.
getItemId() should return unique value for each entry in the list. Try returning position only.
I think the main cause is missing calling notifyDataSetChanged() method.
In fact, your "activity code" is not exactly the activity but a asnyctask that fetch the data. A more common way to use adaper is having a Adaper in your activty along with ListView. In your fetching-data-method(asynctask or loader), call the adaper's change underlying data interface to change the data, and call the adaper's notifyDataSetChanged() method.
A bit psudeo-code may looks like:
Adaper:
public class SearchListViewAdapter extends BaseAdapter {
private JsonArray searchResults;
......
public setDataSet(JsonArray newData) {
searchREsults = newData;
}
......
}
Activity:
public class MyActivity extends Activity {
ListView mResultListView;
SearchListViewAdaper mResultViewAdaper;
#override
OnCreate(...) {
......
//init mResultListView
mResultListView = (ListView) findViewById(R.id.xxxx);
mResultViewAdaper = new SearchListViewAdapter();
mResultListView.setAdapter(mResultViewAdaper);
......
}
......
}
AsyncTask:
public fetchDataTask extends AsyncTask {
......
onPostExecute(JsonArray records) {
mResultViewAdaper.setDataSet(records);
// IMPORTANT: notify data change
mResultViewAdaper.notifyDataSetChanged();
}

Can't figure out correct argument form - calling a method from within a static nested class in Java

I'm testing code copied from a Java Android examples site. I'm trying to modify it to start a new activity when a user clicks into a row of the current activity. So I'm using the Intent method but I'm not able to figure out how to reference the current View instance argument to the Intent method.
I've tried dozens of combinations, and spent 2 days researching. This must seem basic to many of you I know, but my apologies, this is week #2 for me learning Java, Eclipse and the Android SDK (target= API 8)
public class CustomListViewDemo extends ListActivity {
private EfficientAdapter adap;
private static String[] data = new String[] { "0", "1" };
private static String[] TitleString = new String[] { "Title1", "Title2" };
private static String[] DetailString = new String[] { "Detail1", "Detail2" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
adap = new EfficientAdapter(this);
setListAdapter(adap);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(this, "Click-" + String.valueOf(position),
Toast.LENGTH_SHORT).show();
}
public static class EfficientAdapter extends BaseAdapter implements
Filterable {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Context context;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.context = context;
}
/**
* Make a view to hold each row.
*
*/
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adaptor_content, null);
holder = new ViewHolder();
holder.textLine = (TextView) convertView
.findViewById(R.id.textLine);
holder.buttonLine = (Button) convertView
.findViewById(R.id.buttonLine);
holder.DbuttonLine = (Button) convertView
.findViewById(R.id.DbuttonLine);
holder.textLine2 = (TextView) convertView
.findViewById(R.id.textLine2);
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
// Toast.makeText(context, "Click-" +
// String.valueOf(pos),
// Toast.LENGTH_SHORT).show();
// ******************** ERROR IS LINE BELOW *********
// "No enclosing instance of the type CustomListViewDemo is accessible in scope"
Intent i = new Intent(CustomListViewDemo.this, IntentA.class);
startActivity(i);
}
});
holder.buttonLine.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
Toast.makeText(context,
"Delete-" + String.valueOf(pos),
Toast.LENGTH_SHORT).show();
}
});
holder.DbuttonLine.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
Toast.makeText(context,
"Details-" + String.valueOf(pos),
Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
holder.textLine.setText(TitleString[position]
+ String.valueOf(position));
holder.textLine2.setText(DetailString[position]
+ String.valueOf(position));
return convertView;
}
static class ViewHolder {
TextView textLine;
TextView textLine2;
Button buttonLine;
Button DbuttonLine;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
}
}
I have seen many examples about how to refer to outer members of nested classes but not found a good example on find the view instance of an outer class for use as a method argument. Can anyone point me in the right direction?
If you look at the docs, the constructor you're invoking (new Intent(CustomListViewDemo.this, IntentA.class)), is this one:
public Intent (Context packageContext, Class<?> cls)
Since you're already storing a Context, you can fix your problem by using new Intent(this.context, IntentA.class) instead.
CustomListViewDemo.this
For this to work, you need an instance.
In a static nested class, there is no outer instance.
You have to either make the class "non-static", or explicitly pass a reference to a CustomListViewDemo instance around that you want to use here.
EfficientAdapter is a static class so you don't necessarily have an instance of CustomListViewDemo that you can use yet. Static implies that the class can be used without an instance, hence your error
"No enclosing instance of the type CustomListViewDemo is accessible in scope"
You have two options here.
1) Go with dmon's suggestion and use the context you have stored:
Intent i = new Intent(context, IntentA.class);
2) Do not make EfficientAdapter a static class (what is the reason for having it static?)

Categories