Custom array push data with loop - java

I have a custom class to data set User.java
public class User {
public int icon;
public String title;
public User(){
super();
}
public User(int icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
Also have a custom adapter UserAdapter.java
public class UserAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
User data[] = null;
public UserAdapter(Context context, int layoutResourceId, User[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.list_image);
holder.txtTitle = (TextView)row.findViewById(R.id.title);
row.setTag(holder);
}
else
{
holder = (UserHolder)row.getTag();
}
User User = data[position];
holder.txtTitle.setText(User.title);
holder.imgIcon.setImageResource(User.icon);
return row;
}
static class UserHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
I am trying to push data from webservice with the code
public User user_data[] = new User[500];
try {
JSONObject object_exc = response;
JSONArray jArray = object_exc.getJSONArray("exercise");
for (int i = 0; i < jArray.length(); i++) {
JSONObject object = jArray.getJSONObject(i);
user_data[i] = new User(R.drawable.nopic, object.getString("name"));
}
}catch (Exception e){
}
But it is returning null exception where as
User user_data[] = new User[]
{
new User(R.drawable.weather_cloudy, "Cloudy"),
new User(R.drawable.weather_showers, "Showers"),
new User(R.drawable.weather_snow, "Snow"),
new User(R.drawable.weather_storm, "Storm"),
new User(R.drawable.weather_sunny, "Sunny")
};
this is working fine. Please some one help

Try to use ArrayList instead of User[] array.
ArrayList<User> list = new ArrayList<User>();
To add a user to this list.
Just like:
list.add(new User(xxx, yyy));

IMHO there are a couple of problem in your code.
1 - Json file source
JSONArray jArray = object_exc.getJSONArray("exercise");
The constructor request a string that represent a json string. Obviously "exercise" is not a valid json. So you will never find "name" field..so the problem is here!!!
Improvements
2 - Using pure array structure
Maybe is better use an ArrayList is a better option for next manipulation data. (for example sorting!)
3 - object.getString(String abc)
I suggest you to use
object.optString("name", "no_name")
in this way you can put a default return value and avoid other problems. read this SO thread
JSON: the difference between getString() and optString()

Related

creating a custom listview, but values contain "#" and what seems like a C pointer

![](https://scontent-dub4-1.xx.fbcdn.net/v/t1.15752-9/43125544_1705062639616259_4425322847673516032_n.jpg?_nc_cat=102&oh=641ab52118c35e228d9aba28076dbca8&oe=5C16DD7E)
this is my custom adapter class
public class CustomAdapter extends ArrayAdapter<Receipt> {
private Context mContext;
private ArrayList<Receipt> receiptList;
public CustomAdapter(Context context, ArrayList<Receipt> list) {
super(context, 0 , list);
mContext = context;
receiptList = list;
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.custom_list_view,parent,false);
Receipt receipt = receiptList.get(position);
TextView name =listItem.findViewById(R.id.textView_name);
name.setText(receipt.getShopName());
TextView release =listItem.findViewById(R.id.textView_total);
release.setText(receipt.getShopTotal());
return listItem;
}
}
my receipt class
public class Receipt {
private String mShopName;
private String mShopTotal;
public Receipt(String mShopName, String mShopTotal) {
this.mShopName = mShopName;
this.mShopTotal = mShopTotal;
}
public String getShopName() {
return mShopName;
}
public String getShopTotal() {
return mShopTotal;
}
}
and here is my populateListView method
private ArrayList populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<Receipt> receiptList = new ArrayList<>();
while (data.moveToNext()) {
mFilteringDatabase.takeInRow(data.getString(1));
String displayedScreen = mFilteringDatabase.shopName();
String displayedTotal= (mFilteringDatabase.total());
receiptList.add(new Receipt(displayedScreen,displayedTotal));
}
mAdapter= new CustomAdapter(getContext(),receiptList);
return receiptList;
}
there seems to be some issue with the receipt class, as if i override the toString with a "return "test" " line, the error disappears, but only displays "test" of course
thanks in advance guys
edit, just to answer some of your questions, the reason i dont believe it is the scanner, is because when i just use string as the ArrayList type, and pass in only 1 value, the data comes in fine from the database, ie
, this is the code that fixes the issue but only for 1 of the 2 values (i.e. i can concat them and put them on the same line, but i want one right aligned and one left aligned so it wont work as a normal list view
private ArrayList populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> receiptList = new ArrayList<>();
while (data.moveToNext()) {
mFilteringDatabase.takeInRow(data.getString(1));
String displayedScreen = mFilteringDatabase.shopName();
receiptList.add(displayedScreen);
}
return receiptList;
}

what happens when notifyDataSetChanged() is called on object of a class extending Base Adapter

I was reviewing code on Android but don't understand what is happenning when notifyDataSetChanged() is called on an object of a class extending BaseAdapter.
In the code, channelListAdapter.notifyDataSetChanged() was called.
Here is the code of the ChannelListAdapter class:
public class ChannelListAdapter extends BaseAdapter {
Field[] fields;
Context context;
List<Channels> channelList = null;
String dateString, likeData, ab, imageData;
Channels item;
DBVideos dbVideos;
VideoListAdapter videoListAdapter;
MostRecentFragment parentFragment;
public boolean loadingMoreChannels;
public boolean noMoreChannelFound;
Map<String, Boolean> map = new HashMap<String, Boolean>();
Map<String, Integer> totalLikeCount = new HashMap<String, Integer>();
public Map<String, Boolean> timerMap = new HashMap<String, Boolean>();
Map<String, List<Videos>> mapVideos = new HashMap<String, List<Videos>>();
public ChannelListAdapter(Context context) {
this.context = context;
}
public Map<String, List<Videos>> getMapVideos() {
return mapVideos;
}
public void setMapVideos(Map<String, List<Videos>> mapVideos) {
this.mapVideos = mapVideos;
}
public ChannelListAdapter(Context context, List<Channels> channelList) {
this.context = context;
// listener = new NewsFeedListener(context, map, totalLikeCount);
// listener.setListAdapter(this);
this.channelList = channelList;
}
public ChannelListAdapter(Context context, List<Channels> channelList, MostRecentFragment parentFragment) {
this.context = context;
this.parentFragment = parentFragment;
this.channelList = channelList;
}
public String getLastFeedModificationTime() {
Channels lastNews = channelList.get(channelList.size() - 1);
return lastNews.getLastModifyDate();
}
public void setNewsList(List<Channels> channelList) {
this.channelList = channelList;
}
#Override
public int getCount() {
return channelList.size();
}
#Override
public Object getItem(int position) {
return channelList.get(position);
}
#Override
public long getItemId(int position) {
return channelList.indexOf(getItem(position));
}
public static class ViewHolder {
public TextView channelTitle;
public ImageView imgProcess;
ListView videoListView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = (View) mInflater.inflate(R.layout.channel_list_item, null);
holder.channelTitle = (TextView) convertView.findViewById(R.id.tv_channel_name);
holder.imgProcess = (ImageView) convertView.findViewById(R.id.img_process);
holder.videoListView = (ListView) convertView.findViewById(R.id.list_videos);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = (Channels) getItem(position);
final ViewHolder finalHolder = holder;
holder.channelTitle.setText(item.getTitle());
if (mapVideos.size() > 0 && mapVideos.containsKey(item.getId())) {
} else {
Glide.with(context).load("http://4.bp.blogspot.com/-rSoHhekcu9A/T6PQ6d8mKSI/AAAAAAAAASg/hStx9Mg18fc/s1600/22.gif").asGif().placeholder(R.drawable.img_loading).crossFade()
.into(holder.imgProcess);
String url = null;
url = context.getString(R.string.url_6e_channel_context)+CommonUtils.getEncodedUrl(context, context.getString(R.string.url_to_retive_all_video_selected_channel_first)+item.getId())+"+ContentType:Indigo+Video'&rowlimit=3&"+CommonUtils.getEncodedUrl(context,context.getString(R.string.url_to_retive_all_video_selected_channel_sec));
System.out.println("url ="+url);
ServiceCallAsync sca = new ServiceCallAsync(context, null,"Get", null, url, new AsyncResponse() {
#Override
public void processFinish(Object output) {
ServiceResponse serviceResponse = (ServiceResponse) output;
if(serviceResponse.getCode()==200){
parseDataAndStoreinDb(serviceResponse.getData(),finalHolder);
}else{
}
}
});
sca.execute();
}
if (position == channelList.size() - 1) {
if (parentFragment != null && !loadingMoreChannels && !noMoreChannelFound) {
loadingMoreChannels = true;
parentFragment.loadMore();
}
}
return convertView;
}
protected void parseDataAndStoreinDb(String data, ViewHolder finalHolder) {
List<Videos> videosList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(data);
JSONObject dObj = mainObj.getJSONObject("d");
JSONObject queryObj = dObj.getJSONObject("query");
JSONObject primaryQueryObj = queryObj.getJSONObject("PrimaryQueryResult");
JSONObject releventObj = primaryQueryObj.getJSONObject("RelevantResults");
JSONObject tableObj = releventObj.getJSONObject("Table");
JSONObject rowsObj = tableObj.getJSONObject("Rows");
JSONArray resultArray = rowsObj.getJSONArray("results");
for(int i = 0; i<resultArray.length();i++){
Map<String ,String> videoFieldsMap=new HashMap<String, String>();
JSONObject resultObj= resultArray.getJSONObject(i);
JSONObject cellesObj= resultObj.getJSONObject("Cells");
JSONArray resultInnerArray = cellesObj.getJSONArray("results");
for(int j = 0; j<resultInnerArray.length();j++){
JSONObject obj= resultInnerArray.getJSONObject(j);
//System.out.println("obj ="+obj.getString("Key"));
videoFieldsMap.put(obj.getString("Key"), obj.getString("Value"));
}
videoFieldsMap.put("ListId", item.getId());
Videos video = convertMapToVideoModel(videoFieldsMap);
System.out.println("video convertedMap ="+video);
videosList.add(video);
}
if(dbVideos == null ){
dbVideos = new DBVideos(context);
}
dbVideos.insertVideos(videosList);
// mapVideos.put(item.getId(), videosList);
setVideoListAdapter(videosList,finalHolder);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setVideoListAdapter(List<Videos> list, ViewHolder finalHolder) {
if(videoListAdapter == null){
videoListAdapter = new VideoListAdapter(context, list,parentFragment);
}
videoListAdapter.setVideoList(list);
System.out.println("list ="+list.size());
System.out.println("list ="+list.get(1));
finalHolder.videoListView.setAdapter(videoListAdapter);
finalHolder.videoListView.setVisibility(View.VISIBLE);
finalHolder.imgProcess.setVisibility(View.GONE);
ListHeightUtils.setListViewHeightBasedOnChildren(finalHolder.videoListView);
}
private Videos convertMapToVideoModel(Map<String, String> videoFieldsMap){
Class clazz=Videos.class;
Object object = null;
System.out.println("videoFieldsMap ="+videoFieldsMap);
try{
object=clazz.newInstance();
for(Field field:clazz.getDeclaredFields()){
field.setAccessible(true);
System.out.println("field =="+videoFieldsMap.get(field));
field.set(object, videoFieldsMap.get(field.getName()));
}
System.out.println("object ="+object.toString());
}catch(Exception e){
e.printStackTrace();
}
return (Videos)object;
}
}
The Adapter defines the rules to display a list of items in a View - it is usually in the context of a ListView or RecyclerView (but really can be a multitude of things). The view is not aware of when the underlying dataset changes, so after its initial draw, it needs to be told when its data is no longer the most up-to-date.
Say you have the following list:
[A, B, C]
At some point, the user hits an API and the list is updated:
[A, B, C, D, E, F]
The ListView where this list is displayed will still only show:
[A, B, C]
When you call notifyDataSetChanged() on the adapter that is attached to the ListView, it will then update the ListView to show the full new dataset:
[A, B, C, D, E, F]
It is possible too, depending on what kind of adapter you're using, to notify that the entire dataset has changed, or to do more specific update calls like RecyclerView's notifyItemChanged, notifyItemRemoved, notifyItemMoved etc.
From the docs notifyDataSetChanged() :
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
There might be requirement in your application where you want to update the ListView when ever the data set binded to that listview has undergone change like add , update or delete .
To achieve this Android provides a way to call notifyDataSetChanged() for an ArrayAdapter or a BaseAdapter which will update the listview .
See an example here.

Convert JSON values from Integer to String

I am using an AsyncTask to connect to the following URL:
https://api.themoviedb.org/3/movie/upcoming?api_key=6572f232190d6b55ec917726dab87783
One of the values I am having trouble with is the genre_id. As it is a JSONArray I add the values to an ArrayList. I then later want to convert these values to the String correspondence which are found here:
http://api.themoviedb.org/3/genre/movie/list?api_key=6572f232190d6b55ec917726dab87783
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre_ids");
ArrayList<Integer> genre = new ArrayList<Integer>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add(genreArry.optInt(j));
}
I'm just wondering what is the best way to do this? I am a displaying a ListView of all the information and for each row all the information is correct. I just need to convert the Genre id into the corresponding String. I have tried the code below but the TextView is always overwritten by the last value. Does anyone know of a better way to do this?
private void getGenre(int genre) {
for (int i = 0; i < genreList.size(); i++) {
Log.d("THE", "THE GENRE ADAPTER RETRIEVED IS" + i + genreList.get(i).getId() + genreList.get(i).getName());
if (genreList.get(i).getId() == genre) {
String name = genreList.get(i).getName();
mGenre.setText(name);
}
}
Solved.
I managed to get this working by doing a check in the onPostExecute of my AsyncTask
try {
JSONObject json = new JSONObject(result);
JSONArray movies = json.getJSONArray("results");
for (int i = 0; i < movies.length(); i++) {
JSONObject obj = movies.getJSONObject(i);
//Create Movie Object
Movie movie = new Movie();
//get values from JSON
movie.setTitle(obj.getString("original_title"));
movie.setPopularity(obj.getString("popularity"));
movie.setYear(obj.getString("release_date"));
movie.setThumbnailUrl(obj.getString("poster_path"));
movie.setOverView(obj.getString("overview"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre_ids");
ArrayList<Integer> genre = new ArrayList<Integer>();
ArrayList<String> genreName = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add(genreArry.optInt(j));
for (int zz = 0; zz < myGenreList.size(); zz++) {
if (myGenreList.get(zz).getId() == genre.get(j)) {
String name = myGenreList.get(zz).getName();
genreName.add(name);
}
}
}
movie.setGenre(genre);
movie.setGenreName(genreName);
I prefer Volley instead of AsyncTask for simplicity, but you are more than welcome to use either. Note, AsyncTask will require quite a bit more work.
From what I have provided here, you should be able to get my screenshot after building the ListView item XML.
I loosely followed this guide to get started quickly.
Screenshot
Movie.java - Model Object
public class Movie {
private int id;
private String title;
private List<String> genres;
public Movie() {
this(-1, null);
}
public Movie(int id, String title) {
this.id = id;
this.title = title;
this.genres = new ArrayList<String>();
}
public void addGenre(String s) {
this.genres.add(s);
}
public String getTitle() {
return title;
}
public List<String> getGenres() {
return genres;
}
}
MovieAdapter.java - ListView adapter
public class MovieAdapter extends ArrayAdapter<Movie> {
private final int layoutId;
public MovieAdapter(Context context, List<Movie> objects) {
super(context, 0, objects);
layoutId = R.layout.item_movie;
}
private static class ViewHolder {
TextView title;
TextView genres;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Movie movie = getItem(position);
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layoutId, parent, false);
viewHolder.title = (TextView) convertView.findViewById(R.id.movie_title);
viewHolder.genres = (TextView) convertView.findViewById(R.id.movie_genres);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.title.setText(movie.getTitle());
viewHolder.genres.setText(String.valueOf(movie.getGenres()));
// Return the completed view to render on screen
return convertView;
}
}
MainActivity.java
public class MainActivity extends Activity {
private static final String GENRES_URL = "http://api.themoviedb.org/3/genre/movie/list?api_key=6572f232190d6b55ec917726dab87783";
private static final String MOVIES_URL = "https://api.themoviedb.org/3/movie/upcoming?api_key=6572f232190d6b55ec917726dab87783";
private HashMap<Integer, String> genreMap = new HashMap<Integer, String>();
private List<Movie> movies = new ArrayList<Movie>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
final MovieAdapter movieAdapter = new MovieAdapter(this, movies);
lv.setAdapter(movieAdapter);
// Build the genres map
JsonObjectRequest request1 = new JsonObjectRequest(GENRES_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray genres = response.getJSONArray("genres");
for (int i = 0; i < genres.length(); i++) {
JSONObject genre = genres.getJSONObject(i);
int id = genre.getInt("id");
String name = genre.getString("name");
genreMap.put(id, name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Network error", error.getMessage());
}
}
);
VolleyApplication.getInstance().getRequestQueue().add(request1);
JsonObjectRequest request2 = new JsonObjectRequest(MOVIES_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
movieAdapter.clear();
try {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
int movieId = result.getInt("id");
String title = result.getString("original_title");
Movie movie = new Movie(movieId, title);
JSONArray genreIds = result.getJSONArray("genre_ids");
for (int j = 0; j < genreIds.length(); j++) {
int id = genreIds.getInt(j);
String genre = genreMap.get(id);
movie.addGenre(genre);
}
movieAdapter.add(movie);
}
} catch (JSONException e) {
Log.e("JSONException", e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Network error", error.getMessage());
}
}
);
VolleyApplication.getInstance().getRequestQueue().add(request2);
}
}

Loading images in listview asynchronously with callback

I'm using Parse in my app, and in order to load my 'profile' images, I need to retrieve a so called Parsefile. When the Parsefile is downloaded it uses a callback to notify when it's done. Now this is generally a nice way to do things but I encountered a problem with this when using a Listview and downloading the images with an Asynctask.
The problem is as follows:
In my ListView adapter in the getView method, I create an AsyncTask and execute it, this AsyncTask starts the retrieveProfileImage(callBack) function. In my callback I simply start a Runnable on the UI thread to update the ImageView in the View with the new (retrieved Image). The problem however as it seems, is the fact that as soon as I start my AsyncTask, the View is returned. So I can't set the other images to the correct row. I hope my code demonstrates my problem more clearly.
The ListAdapter:
public class FriendListAdapter extends ArrayAdapter<Profile> {
private int resource;
private Context context;
private List<Profile> friends;
private Profile fProfile;
private Bitmap profileImageBitmap;
private ProgressBar friendImageProgressBar;
//ui
private ImageView friendImage;
public FriendListAdapter(Context context, int resource,
List<Profile> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.friends = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView friendName = null;
friendImage = null;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
rowView = inflater.inflate(R.layout.friendslist_row, null);
friendName = (TextView) rowView.findViewById(R.id.fName);
friendImage = (ImageView) rowView
.findViewById(R.id.fImage);
friendImageProgressBar = (ProgressBar) rowView.findViewById(R.id.friendImageProgressBar);
} else {
friendName = (TextView) convertView.findViewById(R.id.fName);
friendImage = (ImageView) convertView.findViewById(R.id.fImage);
friendImageProgressBar = (ProgressBar) convertView.findViewById(R.id.friendImageProgressBar);
}
fProfile = friends.get(position);
DownloadProfileImage dImg = new DownloadProfileImage();
dImg.execute();
friendName.setText(fProfile.getName());
return rowView;
}
private class DownloadProfileImage extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void... arg0) {
Log.d("logpp", "Starting download image for " + fProfile.getName());
fProfile.retrieveProfileImage(new ProfileImageCallback());
return null;
}
}
private class ProfileImageCallback extends GetDataCallback {
#Override
public void done(byte[] bytearray, ParseException e) {
if (e == null) {
Log.d("logpp", "Done downloading image for " + fProfile.getName() + ". Setting bitmap to:" +
" " + friendImage.getId());
profileImageBitmap = BitmapManager
.getBitmapFromByteArray(bytearray);
((Activity) context).runOnUiThread(new UpdateUi());
}
}
}
private class UpdateUi implements Runnable {
#Override
public void run() {
friendImage.setImageBitmap(profileImageBitmap);
friendImage.setVisibility(View.VISIBLE);
friendImageProgressBar.setVisibility(View.INVISIBLE);
}
}
}
The retrieveProfileImage method:
public void retrieveProfileImage(GetDataCallback callBack) {
this.image.getDataInBackground(callBack);
}
I hope someone can help me with this one.
Regards,
Tim
i solved this problem by following code
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.answer_item, null);
TextView name = (TextView) convertView.findViewById(R.id.textView_ans_user_name);
TextView body = (TextView) convertView.findViewById(R.id.textView_ans_user_body);
TextView timestamp = (TextView) convertView.findViewById(R.id.textView_ans_user_timestamp);
final CircularImageView thumbnail = (CircularImageView) convertView.findViewById(R.id.imageView_ans_user);
Parse_answer_model ans = answers.get(position);
name.setText(ans.getAns_by());
body.setText(ans.getAns_body());
SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
sdfAmerica.setTimeZone(TimeZone.getDefault());
String sDateInAmerica = sdfAmerica.format(ans.getCreatedAt());
timestamp.setText(sDateInAmerica);
ParseQuery<User> query = ParseQuery.getQuery("_User");
query.whereEqualTo("username", ans.getAns_by());
query.getFirstInBackground(new GetCallback<User>() {
public void done(User user, ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
img.DisplayImage(user.getprofile_pic_url(), thumbnail, false);
} else {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
put your imageview as final dont make it global and you get image url from geturl() method, it is as defined by parse you can use below example
ParseFile fileObject = (ParseFile) object.get("image_file");
User user = new User();
user = (User) ParseUser.getCurrentUser();
user.setProfile_pic_url(fileObject.getUrl().toString());
user.saveInBackground();
update
last day i found new solution you can get user's data which related to parse object by following code and made some changes in model class,too.
void getchats() {
pd.show();
ParseQuery<Parse_chat_dialogs> query = ParseQuery.getQuery("chat_dialogs");
query.addDescendingOrder("updatedAt");
query.whereContains("users", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<Parse_chat_dialogs>() {
public void done(List<Parse_chat_dialogs> dilogs, ParseException e) {
if (e == null) {
pd.hide();
dialoglist = (ArrayList<Parse_chat_dialogs>) dilogs;
adp = new ChatDialogAdapter(Chat_list.this, dialoglist);
list.setAdapter(adp);
for (int i = 0; i < dialoglist.size(); i++) {
ParseQuery<User> query = ParseQuery.getQuery("_User");
query.whereEqualTo("username", dialoglist.get(i).getUsers().trim()
.replace(ParseUser.getCurrentUser().getUsername(), "").replace(",", ""));
User user = new User();
try {
user = query.getFirst();
dialoglist.get(i).setFirstname(user.getFirstname());
dialoglist.get(i).setLastname(user.getLastname());
dialoglist.get(i).setProfileurl(user.getprofile_pic_url());
adp.notifyDataSetChanged();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} else {
Toast.makeText(Chat_list.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
as in above example i added three new param in parseobejct model class for storing values of user's firstname ,lastname and profile url.
i am also sharing model class for getting more idea
#ParseClassName("chat_dialogs")
public class Parse_chat_dialogs extends ParseObject {
private String firstname;
private String lastname;
private String profileurl;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getProfileurl() {
return profileurl;
}
public void setProfileurl(String profileurl) {
this.profileurl = profileurl;
}
/////////////////////////////////////////////////////////////////////////////
public String getLast_message() {
return getString("last_message");
}
public void setLast_message(String value) {
put("last_message", value);
}
public String getUsers() {
return getString("users");
}
public void setUsers(String value) {
put("users", value);
}
}
How about this!
Instead of using AsyncTask in the adapter class, use it in the MainActivity where you set the adapter for the listview. And in your done method in the Callback or the postExecute update the object/objects and call notifyDataSetChanged().
So, essentially you could have an update method in your adapter class, say, like this,
public void updateObject(int pos, byte[] byteArray){
//Assuming your Profile Object has some member to store this image data
friends.get(pos).setImageData(byteArray); //friends is the list in adapter class and setImageData may be the setter in your Profile object class
notifyDataSetChanged();
}
and in the getView(), you could do something like this
profileImageBitmap = BitmapManager
.getBitmapFromByteArray(friends.get(pos).getImageData);
friendImage.setImageBitmap(profileImageBitmap);

how to send string array one class to another class in android

MainMenulist.java In this class string array store all values public String[] itemcodes; i want access itemcodes to Main.java
Main.java
JSONArray json = jArray.getJSONArray("mainmenu");
list=(ListView)findViewById(R.id.mainmenulist);
adapter=new MainMenulist(this, json);
list.setAdapter(adapter);
MainMenulist.java
public class MainMenulist extends BaseAdapter {
protected static Context Context = null;
int i;
public String editnewmainmenu,menuname;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname,itemcode;
public String[] itemnames,itemcodes;
HashMap<String, String> map = new HashMap<String, String>();
public MainMenulist(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.itemcodes=new String[imageArrayJson.length()];
try {
for (i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("menuimage");
itemname = image.getString("menuname");
itemcode=image.getString("menucode");
itemnames[i] = itemname;
itemcodes[i]=itemcode;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(itemnames[i]);
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public int getCount() {
return mImages.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;
vi = inflater.inflate(R.layout.mainmenulistview, null);
final TextView text = (TextView) vi.findViewById(R.id.menutext);
ImageView image = (ImageView) vi.findViewById(R.id.menuimage);
System.out.println(itemcodes[position]);
image.setImageBitmap(bmps[position]);
text.setText(itemnames[position]);
text.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(itemcodes[position].equals("1"))
{
Intent intent = new Intent(Context, FoodMenu.class);
System.out.println("prakash");
Context.startActivity(intent);
}
else {
Toast.makeText(Context, "This Feauture is not yet Implemented",4000).show();
}
}
});
return vi;
}
}
MainMenulist.java System.out.println(itemcodes[position]); here i print all the codes .no w i want print same result in Main.java
Write a bean which implements serlizable,write setter and getter method for your array(itemnames) as follows
class Bean implements Serializable{
String itemnames[];
public Hashtable getItemnames() {
return itemnames;
}
public void setItemnames(String itemnames[]) {
this.itemnames= itemnames;
}
}
And write foollowing code in calling activity
Bean b = new Bean();
b.setItemnames(itemnames);
Intent i=new Intent();
i.setClass(A.this,B.class);
i.putExtra("itemnames", b);
startActivity(i);
And retrieve in called activity as follows
Bean obj = (Bean) getIntent().getSerializableExtra("itemnames");// TypeCasting
String itemname[] = (Hashtable) obj.getItemnames();
There are two ways to do this:
In your code:
public String[] itemnames,itemcodes; make that arrays as static like below
public static String[] itemnames,itemcodes;
And then use `Main.java` file by calling:
System.out.println(MainMenulist.itemcodes[position]);
System.out.println(MainMenulist.itemnames[position]);
2) Parse JSON in Main.java which you have pass to MainMenulist.java
public MainMenulist(Context context, JSONArray imageArrayJson)

Categories