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);
}
}
Related
I am new to android development and I started working on an expandable RecyclerView. Now My problem is that my child (sub-modules) list is populated dynamically from the selected parent (Module) on the expandable RecyclerView. I tried using a for loop but only the last child list is populated when I open. I was just wondering if there is a way I could implement an item click listener to just return the single selected module.
Here is my adapter:
public class ReportAdapter extends ExpandableRecyclerViewAdapter<ModuleViewHolder, DoiViewHolder> {
Context context;
public ReportAdapter(List<? extends ExpandableGroup> groups, Context context) {
super(groups);
this.context = context;
}
#Override
public ModuleViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_module,parent,false);
return new ModuleViewHolder(view);
}
#Override
public DoiViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_doi,parent,false);
return new DoiViewHolder(view);
}
#Override
public void onBindChildViewHolder(DoiViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
ModuleDoi moduleDoi =(ModuleDoi) group.getItems().get(childIndex);
holder.setDoiName(moduleDoi.getName());
}
#Override
public void onBindGroupViewHolder(ModuleViewHolder holder, int flatPosition, ExpandableGroup group) {
holder.setModuleName(group.getTitle());
}
}
Here is my Parent Holder:
public class ModuleViewHolder extends GroupViewHolder implements View.OnClickListener{
TextView moduleName ;
public ModuleViewHolder(View itemView) {
super(itemView);
moduleName = (TextView) itemView.findViewById(R.id.module_name);
}
public void setModuleName(String name){
moduleName.setText(name);
}
}
Here is my Childs holder (Sub Modules)
public class DoiViewHolder extends ChildViewHolder {
TextView doiName;
public DoiViewHolder(View itemView) {
super(itemView);
doiName = (TextView) itemView.findViewById(R.id.module_doi_name);
}
public void setDoiName(String name){
doiName.setText(name);
}
}
Here is where I set the adapter. I am using the
moduleDoiList = fetchModuleMenus(APPID, MODULENAME);
fetch the submodules list from a json file. the app id in this case is a constant and the MODULENAME is obtained from the Modules Array list.
JSONArray jsonArray = jsonObject.getJSONArray("RESPONSE");
moduleDoiList = new ArrayList<>();
appModulesList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject eachModuleObject = jsonArray.getJSONObject(i);
MODULES modules = new MODULES(eachModuleObject.getString("MODULENAME"),
eachModuleObject.getString("MODULEID"));
ModulesList.add(modules);
for(int j = 0; j<ModulesList.size(); j++) {
String moduleTitle = ModulesList.get(i).getModuleName();
String MODULENAME = ModulesList.get(i).getModuleName();
moduleDoiList = fetchModuleMenus(APPID, MODULENAME);
appModulesList.add(new AppModules(moduleTitle, moduleDoiList));
}
}
reportAdapter = new ReportAdapter(appModulesList, POIDocsReportsActivity.this);
reportAdapter.notifyDataSetChanged();
rv.setAdapter(reportAdapter);
This is my fetchModulesMenu method:
public List<ModuleDoi> fetchModuleMenus(final String appId, final String moduleId) {
moduleDoiList = new ArrayList<>();
Thread thread = new Thread() {
Handler handler = new Handler();
ProgressDialog progressDialog;
boolean error;
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(POIDocsReportsActivity.this, R.style.Theme_AppCompat_DayNight_Dialog_Alert);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
String url = AppConfig.SERVER_URL + "load_module_menus.php";
HashMap hashMap = new HashMap();
hashMap.put("APPID", appId);
hashMap.put("MODULEID", moduleId);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url, new JSONObject(hashMap), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(response.toString());
error = jsonObject.getBoolean("ERROR");
if (error){
Toast.makeText(POIDocsReportsActivity.this, "MENUS NOT FOUND ", Toast.LENGTH_LONG).show();
}
else{
JSONArray jsonArray = jsonObject.getJSONArray("RESPONSE");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject eachMenu = jsonArray.getJSONObject(i);
ModuleDoi moduleDoi = new ModuleDoi(eachMenu.getString("POINAME"), eachMenu.getString("POICODE"));
moduleDoiList.add(moduleDoi);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(POIDocsReportsActivity.this, "CONNECTION ERROR ", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(POIDocsReportsActivity.this, "NO RESPONSE", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
};
thread.run();
return moduleDoiList;
}
I am using the Thoughtbot Custom Expandable Recycler View
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.
This is my JSON data
{ "products": {
"617491704": {
"user_id": "908",
"product_id": 9683,
"product": "Kishmish Raisins Sonaka 250 gm"
}, "1405688942": {
"user_id": "908",
"product_id": 9683,
"product": "Kishmish Raisins Sonaka 250 gm"}, "617491704": {
"product_id": 9683,
"product": "Kishmish Raisins Sonaka 250 gm"
}}
This is my code to parse this JSON data
public static ArrayList<CartData> ParseData(String response) throws JSONException {
ArrayList<CartData> aluser = null;
JSONObject jsonRoot = new JSONObject(response);
JSONObject jsonObject = jsonRoot.getJSONObject("products");
CartData details1 = new CartData();
aluser = new ArrayList<>();
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject inside = jsonObject.getJSONObject(key);
details1.setId(inside.getString("product_id"));
details1.setProductname(inside.getString("product"));
aluser.add(details1);
}
return aluser;
}
The problem is, it shows only last value of arraylist in ListView. Please suggest, where is the problem in my code.
This is my Adapter for ListView.
private class AdapterCommentListcart extends BaseAdapter {
private Context context;
private List<CartData> alComments;
private LayoutInflater inflater;
public AdapterCommentListcart(Context context, List<CartData> alComments) {
this.context = context;
this.alComments = alComments;
inflater = LayoutInflater.from(this.context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
AdapterCommentListcart.ViewHolder holder = null;
if (mapViewHolder.get(position) == null) {
convertView = inflater.inflate(R.layout.products, null);
holder = initHolder(convertView, position);
attachEvents(holder, position);
convertView.setTag(holder);
mapViewHolder.put(position, convertView);
} else {
holder = (AdapterCommentListcart.ViewHolder) mapViewHolder.get(position).getTag();
}
updateHolder(holder, position);
return mapViewHolder.get(position);
}
#Override
public int getCount()
{
return alComments.size();
}
#Override
public CartData getItem(int position) {
return alComments.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvName;
private TextView tvprice;
}
private AdapterCommentListcart.ViewHolder initHolder(View convertView, int pos) {
AdapterCommentListcart.ViewHolder holder = new AdapterCommentListcart.ViewHolder();
holder.tvName = (TextView) convertView.findViewById(R.id.id);
holder.tvprice = (TextView) convertView.findViewById(R.id.name);
return holder;
}
private void updateHolder(final AdapterCommentListcart.ViewHolder holder, final int pos) {
holder.tvName.setText(alProduct.get(pos).getId());
holder.tvprice.setText(alProduct.get(pos).getProductname());
}
private void attachEvents(AdapterCommentListcart.ViewHolder holder, final int position) {
}
}
Put CartData details1 inside while loop. you created an object only one time, you should create an object every time in the loop.
public static ArrayList<CartData> ParseData(String response) throws JSONException {
ArrayList<CartData> aluser = new ArrayList<>();
JSONObject jsonRoot = new JSONObject(response);
if (jsonRoot == null) {
return aluser;
}
JSONObject jsonObject = jsonRoot.optJSONObject("products");
if (jsonObject == null) {
return aluser;
}
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
if (TextUtils.isEmpty(key)) {
continue;
}
JSONObject inside = jsonObject.optJSONObject(key);
if (inside == null) {
continue;
}
String productId = inside.optString("product_id");
String product = inside.optString("product");
if(TextUtils.isEmpty(product) || TextUtils.isEmpty(productId)) {
continue;
}
CartData details1 = new CartData();
details1.setId(productId);
details1.setProductname(product);
aluser.add(details1);
}
return aluser;
}
Only the problem is this line
CartData details1 = new CartData();
it creates object only one time and you added this same object every time inside while loop so instead of creating object only one time create it every time with new data inside while loop and than add like below.
public static ArrayList ParseData(String response) throws JSONException {
ArrayList<CartData> aluser = null;
JSONObject jsonRoot = new JSONObject(response);
JSONObject jsonObject = jsonRoot.getJSONObject("products");
aluser = new ArrayList<>();
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
CartData details1 = new CartData();
String key = keys.next();
JSONObject inside = jsonObject.getJSONObject(key);
details1.setId(inside.getString("product_id"));
details1.setProductname(inside.getString("product"));
aluser.add(details1);
}
return aluser;
}
****Working code posted****
I am trying to update buttons where the text will be dynamically programmed from an ArrayList. The data is being retrieved from mySQL. I can get the data in and fill the array with what I need (familyMemberArray). However for some reason when the information is gathered, the program does not go on to implementing the "trending" array or the rest of the layout programming, after the array information has been produced.
I need to formulate the data first so I know how big the array is to create the amount of buttons necessary. If I call in a basic String array it populates the buttons just fine. I remember being stuck on this problem on a uni project and ended up giving up because I just could not get it to work and time was ticking. Please put me out of my misery
public class TrendingMealsFragment extends Fragment {
private TableRow tr;
//SQLite Database
private static final String SELECT_SQL = "SELECT * FROM family_account";
private SQLiteDatabase db;
private Cursor c;
private static final String DATABASE_NAME = "FamVsFam.db";
// Logging
private final String TAG = this.getClass().getName();
private static final String EXTRA_CHALLENGE_ID = "boo.famvsfam.challenge_id";
//Results
private JSONArray resultFamilyMember;
private String dbID;
public static final String JSON_ARRAY = "result";
private List<String> familyMemberArray;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openDatabase();
setHasOptionsMenu(true);
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
getRecords();
}
protected void openDatabase() {
db = getActivity().openOrCreateDatabase(DATABASE_NAME, android.content.Context.MODE_PRIVATE, null); // db = SQLiteDatabase.openOrCreateDatabase("FamVsFam", Context.MODE_PRIVATE, null);
}
protected void getRecords() {
dbID = c.getString(0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getData();
/** Declaring an ArrayAdapter to set items to ListView */
familyMemberArray = new ArrayList<>();
//Menu
setHasOptionsMenu(true);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
View view = inflater.inflate(R.layout.activity_resturants, container, false);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar();
/**
ArrayList<String> trending1 = new ArrayList<String>() {
{
add("one");
add("two");
add("three");
add("four");
add("five");
add("six");
add("seven");
add("eight");
add("nine");
add("ten");
add("eleven");
}
};*/
ArrayList<String> trending = new ArrayList<String>() {
{
for(int i = 0; i < familyMemberArray.size() ; i++){
add(familyMemberArray.get(i));
}}
};
// LAYOUT SETTING 1
RelativeLayout root = new RelativeLayout(getActivity());
// root.setId(Integer.parseInt(MEAL_SELECTION_ID));
LayoutParams param1 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
root.setFitsSystemWindows(true);
}
root.setLayoutParams(param1);
//LAYOUT SETTINGS 2 - TOP BANNER - WITH PAGE HEADING
RelativeLayout rLayout1 = new RelativeLayout(getActivity());
LayoutParams param2 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
float topBannerDim = getResources().getDimension(R.dimen.top_banner);
param2.height = (int) topBannerDim;
param2.addRule(RelativeLayout.BELOW, root.getId());
int ele = (int) getResources().getDimension(R.dimen.elevation);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
rLayout1.setElevation(ele);
}
rLayout1.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout1.setLayoutParams(param2);
//TEXT VIEW
TextView text1 = new TextView(getActivity());
text1.setText(R.string.diet_req);
LayoutParams param3 = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
param3.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
text1.setTextColor(Color.parseColor("#8A1F1D"));
text1.setTypeface(Typeface.DEFAULT_BOLD);
text1.setLayoutParams(param3);
//LAYOUT SETTINGS 4
RelativeLayout rLayout4 = new RelativeLayout(getActivity());
LayoutParams param5 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
topBannerDim = getResources().getDimension(R.dimen.top_banner);
param5.height = (int) topBannerDim;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
param5.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.ALIGN_START);
}
param5.addRule(RelativeLayout.BELOW, rLayout1.getId());
rLayout4.setId(R.id.id_relative_4);
rLayout4.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout4.setLayoutParams(param5);
//LAYOUT SETTINGS 5
TableLayout rLayout5 = new TableLayout(getActivity());
rLayout5.setOrientation(TableLayout.VERTICAL);
LayoutParams param7 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
param7.addRule(RelativeLayout.BELOW, rLayout4.getId());
rLayout5.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout5.setLayoutParams(param7);
// List<ToggleButton> togButtStore = new ArrayList<ToggleButton>();
int i = 0;
while (i < trending.size()) {
if (i % 3 == 0) {
tr = new TableRow(getActivity());
rLayout5.addView(tr);
}
ToggleButton toggleBtn = new ToggleButton(getActivity());
toggleBtn.setText(trending.get(i));
toggleBtn.setId(i);
toggleBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Context context = getActivity().getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else {
// The toggle is disabled
}
}
});
tr.addView(toggleBtn);
i++;
}
//LAYOUT SETTINGS 6
FrameLayout youBeenFramed = new FrameLayout(getActivity());
LayoutParams param8 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
param8.addRule(RelativeLayout.BELOW, rLayout5.getId());
youBeenFramed.setBackgroundColor(Color.parseColor("#EEEBAA"));
root.addView(youBeenFramed);
root.addView(rLayout1);
rLayout1.addView(text1);
root.addView(rLayout4);
root.addView(rLayout5);
getActivity().setContentView(root);
return view;
}
public void getData() {
//// TODO: 03/08/2016 Progress Dialogs : on getting data
// final ProgressDialog loading = ProgressDialog.show(getActivity(), "Loading Data", "Please wait...", false, false);
StringRequest strReq = new StringRequest(Request.Method.POST,
PHPConfigURLS.URL_ALL_FAMILY_MEMBERS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
JSONObject j = null;
try {
// loading.dismiss();
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFamilyMember = j.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getDBFamilyName(resultFamilyMember);
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
String id = dbID;
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
// params.put("email", email);
// params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(strReq);
}
private void getDBFamilyName(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
FamilyAccount familyMember = new FamilyAccount();
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
familyMember = new FamilyAccount();
familyMember.setName(json.getString("name"));
familyMember.setID(json.getInt("id"));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the title of the challenge to array list
familyMemberArray.add(familyMember.getName());
}
}
}
Thanks in advance
for some reason when the information is gathered, the program does not go on to implementing the "trending" array or the rest of the layout programming, after the array information has been produced.
That's because the layout doesn't "dynamically" update when you call this when the request finishes.
familyMemberArray.add(familyMember.getName());
You'll have to clear the view, and redo all the view adding again, or "extract" all the view generation code into it's own method that you can call with the parameter of your ArrayList.
Basically, everything between // LAYOUT SETTING 1 and return view (non-inclusive) needs to be moved into a public void generateView(ArrayList<String> familyMemberArray) method that can optionally return the root View that was generated, if necessary.
Then, at the end of getFamilyName(), outside the loop, call that method with your ArrayList.
I need to formulate the data first so I know how big the array is to create the amount of buttons necessary.
I'm not sure I see where you are doing that. Unless you mean here
while (i < trending.size()) {
Which, instead, trending is an entirely different list reference than familyMemberArray, so it won't update either. Though, it contains the exact same data?
ArrayList<String> trending = new ArrayList<String>() {
{
for(int i = 0; i < familyMemberArray.size() ; i++){
add(familyMemberArray.get(i));
}}
};
That block of code looks a bit odd, considering the ArrayList constructor already provides that functionality
ArrayList<String> trending = new ArrayList<String>(familyMemberArray);
*****WORKING CODE****** Credit to cricket_007
FIELDS
public class TrendingMealsFragment extends Fragment {
// Logging
private final String TAG = this.getClass().getName();
//Results
private JSONArray resultFamilyMember;
public static final String JSON_ARRAY = "result";
private ArrayList<String> familyMemberArray;
//Layout
private TableRow tr;
OnCreateView()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_resturants, container, false);
generateView(familyMemberArray);
getData();
return view;
}
GetData()
public void getData() {
StringRequest strReq = new StringRequest(Request.Method.POST,
PHPConfigURLS.URL_ALL_FAMILY_MEMBERS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFamilyMember = j.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getDBFamilyName(resultFamilyMember);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
String id = dbID;
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(strReq);
}
getDBFamilyName()
private void getDBFamilyName(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
FamilyAccount familyMember = new FamilyAccount();
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
familyMember = new FamilyAccount();
familyMember.setName(json.getString("name"));
familyMember.setID(json.getInt("id"));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the title of the challenge to array list
familyMemberArray.add(familyMember.getName());
generateView(familyMemberArray);
}
}
generateView()
public View generateView(ArrayList<String> familyMemberArray) {
...
rLayout5.setLayoutParams(param7);
//Create Buttons
int i = 0;
while (i < familyMemberArray.size()) {
if (i % 3 == 0) {
tr = new TableRow(getActivity());
rLayout5.addView(tr);
}
ToggleButton toggleBtn = new ToggleButton(getActivity());
toggleBtn.setText(familyMemberArray.get(i));
toggleBtn.setId(i);
toggleBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Context context = getActivity().getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else {
// The toggle is disabled
}
}
});
tr.addView(toggleBtn);
i++;
}
...
root.addView(rLayout5);
getActivity().setContentView(root);
return root;
}
}
I am fairly new to android programming and ran to a small problem. I have an activity that lets users select names from a muli-select listview. I can store it in an ArrayList fine but how do I pass that ArrayList as a bundle to be retrieved from the fragment? Thank you for any future answers.
MainActivity.java:
public class MainActivity extends Activity {
ListView myListView;
Button getResult;
ConnectionClass connectionClass;
private ArrayList<String> emp_names_list = new ArrayList<String>();
public ArrayList<Integer> emp_id_list = new ArrayList<Integer>();
MyArrayAdapter myArrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
emp_names_list.add("LOL");
//PAGKUHA NG RESULTS SA DB
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
String query = "select * from users WHERE user_type=3";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
String fname =rs.getString("user_fname");
String lname =rs.getString("user_lname");
String name = String.valueOf(fname)+" "+String.valueOf(lname);
emp_names_list.add(fname);
}
Toast.makeText(getApplicationContext(), "FETCH SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "FETCH FAIL", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
myListView = (ListView)findViewById(R.id.list);
//PARA SA LAYOUT
myArrayAdapter = new MyArrayAdapter(
this,
R.layout.row,
android.R.id.text1,
emp_names_list
);
myListView.setAdapter(myArrayAdapter);
myListView.setOnItemClickListener(myOnItemClickListener);
getResult = (Button)findViewById(R.id.getresult);
getResult.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String result = "";
/*
//getCheckedItemPositions
List<Integer> resultList = myArrayAdapter.getCheckedItemPositions();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + " ";
}
*/
//getCheckedItems
List<String> resultList = myArrayAdapter.getCheckedItems();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + "\n";
}
myArrayAdapter.getCheckedItemPositions().toString();
//Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
//FOR INSERTION ITO USING ARRAYLIST
String samp = "";
String names = "";
samp = myArrayAdapter.getCheckedItems().toString();
List<String> data1 = new ArrayList<String>(Arrays.asList(samp.replace("[","").replace("]","").split(",")));
//data1.add(samp);
for(String name : data1)
{
names = name;
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+names+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
Toast.makeText(getApplicationContext(), "INSERT SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "INSERT FAILED", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
}});
}
OnItemClickListener myOnItemClickListener = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
myArrayAdapter.toggleChecked(position);
}};
private class MyArrayAdapter extends ArrayAdapter<String>{
private HashMap<Integer, Boolean> myChecked = new HashMap<Integer, Boolean>();
public MyArrayAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
for(int i = 0; i < objects.size(); i++){
myChecked.put(i, false);
}
}
public void toggleChecked(int position){
if(myChecked.get(position)){
myChecked.put(position, false);
}else{
myChecked.put(position, true);
}
notifyDataSetChanged();
}
public List<Integer> getCheckedItemPositions(){
List<Integer> checkedItemPositions = new ArrayList<Integer>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItemPositions).add(i);
}
}
return checkedItemPositions;
}
public List<String> getCheckedItems(){
List<String> checkedItems = new ArrayList<String>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItems).add(emp_names_list.get(i));
}
}
return checkedItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
CheckedTextView checkedTextView = (CheckedTextView)row.findViewById(R.id.checkedTextView);
checkedTextView.setText(emp_names_list.get(position));
Boolean checked = myChecked.get(position);
if (checked != null) {
checkedTextView.setChecked(checked);
}
return row;
}
}
}
I have tried the following example but returns null:
Bundle bundle=new Bundle();
bundle.putBundle("bundle_DescriptioneTab",bundle_DescriptioneTab);
bundle.putBundle("bundle_User_Review",bundle_User_Review);
The first thing is that you have to declare your Class as Serializable
public class MyClass implements Serialisable{
}
and using
Bundle bundle = new Bundle();
bundle.putSerialisable("myclass",MyClass);
to send data of only class
And
If you want to send Arraylisyt use:
public class MyClass implements Parcelable{
}
Intent intent = new Intent(this,SecondaryActivity.class);
ArrayList<MyClass> mArrayList = new ArrayList<MyClass>();
and using
intent.putParcelableArrayListExtra("key", mArrayList);
You can store it in an object:
public class Thing implements Serializable {
private ArrayList<String> emp_names_list = new ArrayList<String>();
public ArrayList<Integer> emp_id_list = new ArrayList<Integer>();
[...]
}
And pass it like so:
bundle.putBundle("thing",object_thing);