Related
I tried to build an app that have 5 fragment that displayed using bottom navigation view. I use volley to get the data from database. i have a problem with calling the data. at fragment A. i call the web service and got some data and then display it using recyclerview. But if i move to another fragment ( lets say fragment B) and went back to the fragment A. the data is lost and it just show the standard ui like search widget,spinner widget. All i want to ask is :
where should i put the code to call web service for all my fragment. On the activity that handle the fragment or just on the fragment?
why volley doesn't call data again when i back to the fragment?
this is the code of my mainactivity that contain bottom navigation view with 5 fragments:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkStatusAvialable (getApplicationContext())) {
bottomNavigationView=(BottomNavigationView)findViewById(R.id.main_nav);
frameLayout=(FrameLayout) findViewById(R.id.main_frame);
herbal= new herbal();
crude = new crude();
database=new database();
analysis=new analysis();
compound=new compound();
setFragment(herbal);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
default:
return false;
}
}
});
} else {
Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
this is the example in my fragment which calling web service and then display it using recycler view:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
herbalModels = new ArrayList<>();
kampoModels = new ArrayList<>();
searchHerbal = (EditText) rootView.findViewById(R.id.search_herbal);
searchHerbal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchHerb();
}
});
loadData = (ProgressBar) rootView.findViewById(R.id.loadRecyclerView);
RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
sortData(rootView);
get20DataJamu();
get20DataKampo();
StartRecyclerViewJamu(rootView);
return rootView;
}
private void searchHerb() {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
searchHerbs searchHerbs = new searchHerbs();
ft.replace(R.id.main_frame, searchHerbs);
ft.commit();
}
private void StartRecyclerViewKampo(View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
kampoAdapter = new kampoAdapter(mRecyclerView, getActivity(), kampoModels);
mRecyclerView.setAdapter(kampoAdapter);
kampoAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
kampoModels.add(null);
kampoAdapter.notifyItemInserted(kampoModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
kampoModels.remove(kampoModels.size() - 1);
kampoAdapter.notifyItemRemoved(kampoModels.size());
//add items one by one
int start = kampoModels.size();
int end = start + 20;
loadMoreKampo(start, end);
}
}, 5000);
}
});
}
private void loadMoreKampo(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
kampoAdapter.notifyItemInserted(kampoModels.size());
} catch (JSONException e) {
}
}
kampoAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void get20DataKampo() {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponsekampo" + jsonArray.toString());
Log.d(TAG, "lengthresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerrorkampo" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void StartRecyclerViewJamu(final View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new herbalAdapter(mRecyclerView, getActivity(), herbalModels);
mRecyclerView.setAdapter(mAdapter);
loadData.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mAdapter.notifyDataSetChanged();
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
herbalModels.add(null);
mAdapter.notifyItemInserted(herbalModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
herbalModels.remove(herbalModels.size() - 1);
mAdapter.notifyItemRemoved(herbalModels.size());
//add items one by one
int start = herbalModels.size();
int end = start + 20;
loadMoreJamu(start, end);
}
}, 5000);
}
});
}
private void get20DataJamu() {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
Log.d(TAG, "lengthonresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void loadMoreJamu(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
mAdapter.notifyItemInserted(herbalModels.size());
} catch (JSONException e) {
}
}
mAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void sortData(final View rootView) {
final Spinner spinner = (Spinner) rootView.findViewById(R.id.filter_herbal);
// Create an ArrayAdapter using the string array and a default spinner layout
List<categoriesHerbal> itemList = new ArrayList<categoriesHerbal>();
itemList.add(
new categoriesHerbal(
"1",
"Jamu"
)
);
itemList.add(
new categoriesHerbal(
"2",
"Kampo"
)
);
ArrayAdapter<categoriesHerbal> spinnerAdapter = new ArrayAdapter<categoriesHerbal>(getActivity(), android.R.layout.simple_spinner_item, itemList);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewJamu(rootView);
} else {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewKampo(rootView);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
move your data code in separate class and call it wherever needed.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
/*default:
return false;*/ //no need for this one
}
return true; /*you forget'it*/
}
I am developing the chatbot app. I am using the RecycleView to render the chat of user and bot. I have to show the user listview or text response depend upon his query. All is working until my RecyclerView get's scroll. Whenever my RecyclerView gets scroll it changes the item position. I search a lot and applied every solution but not able to solve my issue.
here is my activity.java
public class HomeActivity extends AppCompatActivity implements AIListener,
View.OnClickListener {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
LinearLayoutManager layoutManager;
private ArrayList<Message> messageArrayList;
private EditText inputMessage;
private RelativeLayout btnSend;
Boolean flagFab = true;
PaytmPGService service = null;
Map<String, String> paytmparam = new HashMap<>();
PrefManager prefManager;
private AIService aiService;
AIDataService aiDataService;
AIRequest aiRequest;
Gson gson;
String food_dish = " ";
double price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
inputMessage = findViewById(R.id.editText_ibm);
btnSend = findViewById(R.id.addBtnibm);
recyclerView = findViewById(R.id.recycler_view_ibm);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(this,messageArrayList);
prefManager = new PrefManager(this);
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int msgCount = mAdapter.getItemCount();
int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (msgCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setAdapter(mAdapter);
this.inputMessage.setText("");
final AIConfiguration configuration = new AIConfiguration("cabc4b7b9c20409aa7ffb1b3d5fe1243",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, configuration);
aiService.setListener(this);
aiDataService = new AIDataService(configuration);
aiRequest = new AIRequest();
btnSend.setOnClickListener(this);
inputMessage.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageView fab_img = findViewById(R.id.fab_img_ibm);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_send_white_24dp);
Bitmap img1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mic_white_24dp);
if (s.toString().trim().length() != 0 && flagFab) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img);
flagFab = false;
} else if (s.toString().trim().length() == 0) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img1);
flagFab = true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
anim_out.setAnimationListener(new Animation.AnimationListener()
{
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
#Override
public void onClick(View v) {
final String inputmessage = this.inputMessage.getText().toString().trim();
if(!inputmessage.equals("")){
new AsyncTask<String, Void, AIResponse>(){
private AIError aiError;
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
try {
return aiDataService.request(request);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
}.execute(inputmessage);
}else {
aiService.startListening();
}
inputMessage.setText("");
}
#Override
public void onResult(AIResponse response) {
int itemNumber = 0;
Log.d("dialogeflow response",response.toString());
try {
JSONObject AIResponse = new JSONObject(gson.toJson(response));
Log.d("json response",AIResponse.toString());
final JSONObject result = AIResponse.getJSONObject("result");
JSONArray contexts = result.getJSONArray("contexts");
final JSONObject fulfillment = result.getJSONObject("fulfillment");
if(contexts.length()>0) {
for(int i = 0;i<contexts.length();i++) {
JSONObject context_items = contexts.getJSONObject(i);
JSONObject paramters = context_items.getJSONObject("parameters");
if (paramters.has("Cuisine")) {
prefManager.setCuisinetype(paramters.getString("Cuisine"));
} else if (paramters.has("Restaurants_name")) {
prefManager.setRestaurant_name(paramters.getString("Restaurants_name"));
}
if (paramters.has("number") && !paramters.getString("number").equals("") && paramters.has("Food_Dishes") && !paramters.getString("Food_Dishes").equals("")) {
itemNumber = Integer.parseInt(paramters.getString("number"));
if (itemNumber <= 2 && price !=0) {
price = 300 + (int) (Math.random() * ((1400 - 300) + 1));
} else {
price = 600 + (int) (Math.random() * ((2200 - 600) + 1));
}
food_dish = paramters.getString("Food_Dishes");
}
}
}
final double finalPrice = price;
final int finalItemNumber = itemNumber;
if(!result.getString("resolvedQuery").matches("payment is done successfully")) {
Message usermsg = new Message();
usermsg.setMessage(result.getString("resolvedQuery"));
usermsg.setId("1");
messageArrayList.add(usermsg);
mAdapter.notifyDataSetChanged();
if (fulfillment.has("speech")) {
Log.d("response of speech", fulfillment.getString("speech"));
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
if (fulfillment.getString("speech").matches("Redirecting you to the Pay-Tm site")) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
getpaytm_params((int) price);
}
}, 2000);
} else {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
if (speech.contains("Your total bill is ₹")) {
Log.d("price", String.valueOf(price));
outMessage.setMessage("Please Confirm your order:- \n" +finalItemNumber +" "+food_dish+" from "+prefManager.getRestaurant_name()+" at Flat No: 20,Galaxy Apartment,Airport Authority Colony,Andheri,Mumbai,Maharashtra 400 047 \n Your total bill is ₹"+price+". \n Do you want to pay by Wallet or by PayTm");
}else{
outMessage.setMessage(speech);
}
outMessage.setId("2");
messageArrayList.add(outMessage);
Log.d("messgae",outMessage.getMessage());
mAdapter.notifyDataSetChanged();
}
}, 2000);
}
} else {
final JSONArray msg = fulfillment.getJSONArray("messages");
for (int i = 0; i < msg.length(); i++) {
if (i == 0) {
Message outMessage = new Message();
JSONObject speechobj = msg.getJSONObject(i);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
} else {
final int itemposition = i;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
try {
JSONObject speechobj = msg.getJSONObject(itemposition);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 5000);
}
}
}
}
}else{
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
}
},2000);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
btnSend.setBackground(getDrawable(R.drawable.recording_bg));
}
#Override
public void onListeningCanceled() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
#Override
public void onListeningFinished() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
}`
my ChatAdapter.java class
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int BOT = 100;
private int BOT_Restaurant_ListView = 101;
private int USER = 102;
private Activity activity;
private PrefManager prefManager;
private int itemposition = -1;
private int menu_itemposition = -1;
private List<Restaurant_List_Model> restaurant_list;
private ArrayList<Message> messageArrayList;
private RestaurantListViewAdapter restaurantListViewAdapter;
private TextToSpeech tts ;
public ChatAdapter(Activity activity, ArrayList<Message> messageArrayList) {
this.activity = activity;
this.messageArrayList = messageArrayList;
tts = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
prefManager = new PrefManager(activity.getApplicationContext());
setHasStableIds(true);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview;
if(viewType == BOT){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_view,parent,false);
}else if(viewType == BOT_Restaurant_ListView){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_restaurant_listview,parent,false);
}else {
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg_view,parent,false);
}
return new ViewHolder(itemview);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if(message.getId()!=null && message.getId().equals("2")){
if(message.getMessage().contains("restaurants") || message.getMessage().contains("restaurant")) {
return BOT_Restaurant_ListView;
}else {
return BOT;
}
}else{
return USER;
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int pic_int = 1;
String filename = null;
final Message message = messageArrayList.get(position);
message.setMessage(message.getMessage());
if (holder.getItemViewType() == BOT_Restaurant_ListView) {
Log.d("inside bot listview msg", String.valueOf(BOT_Restaurant_ListView ));
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
if(itemposition<holder.getAdapterPosition()){
itemposition = holder.getAdapterPosition();
Log.d("itemposition",String.valueOf(itemposition));
String jsonFileContent;
Log.d("cuisine value", prefManager.getCuisinetype());
if (message.getMessage().contains("restaurants")) {
if(!prefManager.getCuisinetype().equals("") && prefManager.getCuisinetype() != null){
Log.d("restauratn has drawn", "greate");
try {
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
Log.d("cuisine value", prefManager.getCuisinetype());
if(message.getMessage().contains("Here are restaurants near you")){
String [] restaurant_Array ={
"indian","french","mexican","italian"
};
int randomNumber = (int) Math.floor(Math.random()*restaurant_Array.length);
filename = restaurant_Array[randomNumber];
Log.d("filename",filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}else {
filename = prefManager.getCuisinetype().toLowerCase() + "_restaurants";
Log.d("filename", filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}
JSONObject restaurantfile = new JSONObject(jsonFileContent);
JSONArray jsonArray = restaurantfile.getJSONArray("restaurants");
for (int i = 0; i < jsonArray.length(); i++) {
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
JSONObject restaurantList = jsonArray.getJSONObject(i);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(restaurantList.getString("name"));
restaurant_list_obj.setLocation(restaurantList.getString("location"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("restaurant_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(restaurantList.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
prefManager.setCuisinetype("");
pic_int = 1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
restaurantListViewAdapter.notifyDataSetChanged();
}
}else if(message.getMessage().contains("Here are some famous food items from "+prefManager.getRestaurant_name()+" restaurant")){
try {
Log.d("menu has draw","greate");
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
Log.d("restaurant name value", prefManager.getRestaurant_name());
jsonFileContent = readFile(R.raw.restaurant_menu);
JSONObject menu_cuisine = new JSONObject(jsonFileContent);
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
if (menu_cuisine.has(prefManager.getRestaurant_name())) {
JSONObject restaurant_menu = menu_cuisine.getJSONObject("Dominos");
Log.d("Chili's American menu", restaurant_menu.toString());
JSONArray menu = restaurant_menu.getJSONArray("menu");
for (int j = 0; j < menu.length(); j++) {
JSONObject menu_obj = menu.getJSONObject(j);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(menu_obj.getString("name"));
restaurant_list_obj.setLocation(menu_obj.getString("cuisine_type"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
//restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(menu_obj.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
restaurantListViewAdapter.notifyDataSetChanged();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
prefManager.setRestaurant_name("");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.d("user_message",message.getMessage());
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
}else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
((ViewHolder) holder).retaurant_listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
} if(holder.getItemViewType()==BOT) {
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
Log.d("inside bot msg", String.valueOf(BOT));
((ViewHolder) holder).bot_msg.setText(message.getMessage());
if(itemposition<holder.getAdapterPosition()) {
itemposition = holder.getAdapterPosition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}if(holder.getItemViewType() == USER) {
((ViewHolder) holder).user_message.setText(message.getMessage());
}
}
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if(holder.isRecyclable()){
Log.d("inside onViewRecycled","great");
// itemposition = holder.getAdapterPosition();
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
private String readFile(int id) throws IOException
{
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String content = "";
String line;
while ((line = reader.readLine()) != null)
{
content = content + line;
}
return content;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView user_message,bot_msg;
private ListView retaurant_listView;
ViewHolder(View itemView) {
super(itemView);
bot_msg = itemView.findViewById(R.id.bot_message);
user_message = itemView.findViewById(R.id.message);
retaurant_listView = itemView.findViewById(R.id.restaurant_items_list_ibm);
}
}
}
Please help me out with this issue.
In gif, you can see the lower list is swap with the upper list and then return back
getting response from server id and name,
public class UpcomingRaces extends Fragment {
private static final String TAG = "UpcomingRaces";
UserSessionManager session;
Button btn_selectloc;
TextView mItemSelected;
String[] listItems = {};
boolean[] checkedItems;
ArrayList<Integer> mUserItems = new ArrayList<>();
ArrayList<String> arrayList = new ArrayList<String>();
String[] listItems1 = {};
ArrayList<String> arrayList1 = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_upcoming_races, container, false);
session = new UserSessionManager(getActivity());
btn_selectloc = (Button) rootView.findViewById(R.id.btn_selectloc);
mItemSelected = (TextView) rootView.findViewById(R.id.tvItemSelected);
getLocations();
listItems = arrayList.toArray(new String[Arrays.asList(listItems).size()]);
checkedItems = new boolean[listItems.length];
listItems1 = arrayList1.toArray(new String[Arrays.asList(listItems).size()]);
btn_selectloc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
mBuilder.setTitle(R.string.dialog_title);
mBuilder.setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean isChecked) {
if(isChecked){
mUserItems.add(position);
}else{
mUserItems.remove((Integer.valueOf(position)));
}
}
});
mBuilder.setCancelable(false);
mBuilder.setPositiveButton(R.string.ok_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
String item = "";
String item1 = "";
for (int i = 0; i < mUserItems.size(); i++) {
item = item + listItems[mUserItems.get(i)];
if (i != mUserItems.size() - 1) {
item = item + ", ";
}
item1 = item1 + listItems1[mUserItems.get(i)];
if (i != mUserItems.size() - 1) {
item1 = item1 + ", ";
}
}
mItemSelected.setText(item1);
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
}
});
return rootView;
}
private void getLocations() {
StringRequest stringRequest = new StringRequest("https://jsonplaceholder.typicode.com/posts",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject("{"response":1,"message":"locations success","data":[{"id":7,"name":"123 Middle School"},{"id":8,"name":"ABC Jr High"},{"id":3,"name":"Brentwood High school"},{"id":2,"name":"Clinton Elementary"},{"id":5,"name":"Iowa High School"},{"id":1,"name":"Jfk middle school"},{"id":6,"name":"Terryville Elementary "},{"id":4,"name":"West Jr high"}]}");
if (obj.getString("response").equals("1")) {
//mProgress.dismiss();
JSONArray res = new JSONArray(obj.getString("data"));
for (int i=0; i<res.length(); i++) {
JSONObject result = null;
result = res.getJSONObject(i);
arrayList.add(result.getString("name"));
arrayList1.add(result.getString("id"));
}
} else {
Toast.makeText(getActivity(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
I want to show the name in setMultiChoiceItems with boolean checkedItems and I want to append checked "id" to TextView mItemSelected.
Also I want to store that checked id in the session.
I have tried in a many ways and couldn't able to solve this issue..please help me to achieve this.
EDITED
public class MainActivity extends AppCompatActivity {
LinearLayout notification_bar_linearlayout;
TextView txtOutput;
private String DEBUG_TAG = "MOVEMENT";
ArrayList<String> arrayList;
ArrayList<Integer> mUserItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOutput = (TextView) findViewById(R.id.output);
mUserItems = new ArrayList<>();
StringRequest stringRequest = new StringRequest("your_url_here",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
arrayList = new ArrayList<>();
response = " {\"response\":1,\"message\":\"locations success\",\"data\":[{\"id\":7,\"name\":\"123 Middle School\"},{\"id\":8,\"name\":\"ABC Jr High\"},{\"id\":3,\"name\":\"Brentwood High school\"}]}";
JSONObject obj = new JSONObject(response);
if (obj.getString("response").equals("1")) {
JSONArray res = obj.getJSONArray("data");
for (int i=0; i< res.length(); i++) {
JSONObject val = res.getJSONObject(i);
arrayList.add(val.getString("name"));
}
LoadAlert();
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void LoadAlert()
{
String[] listItems = arrayList.toArray(new String[arrayList.size()]);
boolean[] checkedItems = new boolean[listItems.length];
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
mBuilder.setTitle("SELECT ITEMS");
mBuilder.setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean isChecked) {
if(isChecked){
mUserItems.add(position);
}else{
mUserItems.remove((Integer.valueOf(position)));
}
}
});
mBuilder.setCancelable(false);
mBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
String items = "";
for (int i = 0;i < mUserItems.size();i++)
{
items += "" + mUserItems.get(i) + ", ";
}
txtOutput.setText(items);
}
});
mBuilder.show();
}
Hope it will works.!
I'm inflating dynamic view to linear layout but it displays reversely.
try {
JSONArray jsonArray = new JSONArray(tooteet.getMeasureJson());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Measure measureData = new Measure();
measureData.id = jsonObject.optString("id");;
measureData.tooteetId = jsonObject.optString("tooteetId");
measureData.laneId = jsonObject.optString("laneId");
measureData.startDate = jsonObject.optString("startDate");
measureData.endDate = jsonObject.optString("endDate");
measureData.description = jsonObject.optString("text");
measureData.value = jsonObject.optDouble("value");
measureData.measureTypeId = jsonObject.optInt("measureTypeId");
measureData.description = jsonObject.optString("text");
measureData.isTimeSet =jsonObject.optBoolean("isTimeSet");
mMeasureList.add(measureData);
addMeasureView(measureData, i);
}
} catch (Exception e) {
Log.d("FeedMeasure", "Exception: "+e.toString());
}
where i'm getting log value for tooteet.getMeasureJson() is
onCreate -- tooteet.getMeasureJson(): [{"id":"3fb2af41-201d-4aca-9479-42af6cca5947","tooteetId":"3d923a95-d8d8-4478-b336-c995cc77407d","laneId":"00000000-0000-0000-0000-000000000000","value":11111,"text":"","measureTypeId":1,"isTimeSet":false},{"id":"ecab9659-7eb5-417a-8f5e-f769629957ae","tooteetId":"3d923a95-d8d8-4478-b336-c995cc77407d","laneId":"00000000-0000-0000-0000-000000000000","value":22222,"text":"","measureTypeId":1,"isTimeSet":false}]
Here I'm adding measure view using below method
private void addMeasureView(final Measure measure, int position) {
Log.d("ss","adding measure data value ________________"+measure.value+" position __________"+position);
final View parent = getLayoutInflater().inflate(R.layout.view_measure_tooteet_item, mDisplayContainer, false);
final TextView txtDescription, txtValues, txtStartDateTime, txtEndDateTime, labelTaxIncluded, labelTaxColon;
final ImageView imgEdit, imgDelete;
final LinearLayout lnrDescription, lnrStartLayout, lnrEndLayout;
final View mViewDivider;
txtDescription = (TextView) parent.findViewById(R.id.txt_description);
txtValues = (TextView) parent.findViewById(R.id.values);
txtStartDateTime = (TextView) parent.findViewById(R.id.start_date_and_time);
txtEndDateTime = (TextView) parent.findViewById(R.id.end_date_and_time);
mViewDivider = (View) parent.findViewById(R.id.view_divider);
imgEdit = (ImageView) parent.findViewById(R.id.edit);
imgDelete = (ImageView) parent.findViewById(R.id.delete);
lnrDescription = (LinearLayout) parent.findViewById(R.id.lnr_description);
lnrStartLayout = (LinearLayout) parent.findViewById(R.id.lnr_start_layout);
lnrEndLayout = (LinearLayout) parent.findViewById(R.id.lnr_end_layout);
if(tooteet.isOwner(getUserPreference())){
imgDelete.setVisibility(View.VISIBLE);
imgEdit.setVisibility(View.VISIBLE);
}else{
imgDelete.setVisibility(View.GONE);
imgEdit.setVisibility(View.GONE);
}
if(measure.getValue() > 0) {
txtValues.setVisibility(View.VISIBLE);
if (measure.getValue() % 1 == 0) {
txtValues.setText("" + (int) measure.getValue()+ " "+MeasureTypeSelector.getMeasureTypeById(FeedMeasureDetailsActivity.this, measure.getMeasureTypeId()));
} else {
txtValues.setText("" + measure.getValue()+ " "+ MeasureTypeSelector
.getMeasureTypeById(FeedMeasureDetailsActivity.this, measure.getMeasureTypeId()));
}
}else{
txtValues.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getDescription())){
lnrDescription.setVisibility(View.VISIBLE);
txtDescription.setText(measure.getDescription());
}
else{
lnrDescription.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getStartDate())) {
lnrStartLayout.setVisibility(View.VISIBLE);
txtStartDateTime.setText("" + DateConversion.getDateAndTime(measure.getStartDate(), "MMMM dd, yyyy hh:mm a"));
}
else{
lnrStartLayout.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getEndDate())) {
lnrEndLayout.setVisibility(View.VISIBLE);
txtEndDateTime.setText("" + DateConversion.getDateAndTime(measure.getEndDate(), "MMMM dd, yyyy hh:mm a"));
}else{
lnrEndLayout.setVisibility(View.GONE);
}
//
// if(position < mMeasureList.size()){
// mViewDivider.setVisibility(View.VISIBLE);
// }else{
// mViewDivider.setVisibility(View.GONE);
// }
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int pos = (Integer) v.getTag();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setTitle(R.string.delete);
builder.setMessage(R.string.delete_tooteet_measure_tuple);
builder.setPositiveButton(R.string.yes_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!BDevice.isInternetConnected(FeedMeasureDetailsActivity.this)) {
AlertUtils.showNetworkAlert(FeedMeasureDetailsActivity.this);
return;
}
final Dialog pd = UiUtils.getSpinnerDialog(FeedMeasureDetailsActivity.this, getString(R.string.loading));
pd.show();
getDairyLineApi().deleteMeasureTooteet(mMeasureList.get(pos).getId(), tooteet.getLaneId(), new ResponseHandler() {
#Override
public void onSuccess(int statusCode, String content) {
dismiss();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setMessage(R.string.deleted_successfully);
builder.setPositiveButton(R.string.ok_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDisplayContainer.removeView(parent);
mMeasureList.remove(pos);
tooteet.setMeasureJson(Measure.getMeasureDetailJSON(mMeasureList));
mTooteetManager.updateMeasureTooteet(tooteet, tooteet.getId());
}
});
builder.create().show();
}
#Override
public void onFailure(int statusCode, String content) {
dismiss();
if (!TextUtils.isEmpty(content)) {
AlertUtils.showAlert(FeedMeasureDetailsActivity.this, content);
}
}
private void dismiss() {
if (pd != null && !isFinishing()) {
pd.dismiss();
}
}
});
}
});
builder.setNegativeButton(R.string.no_caps, null);
builder.create().show();
}
});
imgEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int pos = (Integer) v.getTag();
MeasureTooteetSelector measureTooteetSelector = new MeasureTooteetSelector();
measureTooteetSelector.openMeasureDetailSelector(FeedMeasureDetailsActivity.this, mMeasureList.get(pos),
new MeasureTooteetSelector.OnMeasureDetailSelectListener() {
#Override
public void onMeasureSelect(final Measure measureData) {
if (!BDevice.isInternetConnected(FeedMeasureDetailsActivity.this)) {
AlertUtils.showNetworkAlert(FeedMeasureDetailsActivity.this);
return;
}
final Dialog pd = UiUtils.getSpinnerDialog(FeedMeasureDetailsActivity.this, getString(R.string.loading));
pd.show();
if (measureData != null) {
mMeasureList.set(pos, measureData);
}
getDairyLineApi().updateMeasureTooteet(mMeasureList.get(pos), new ResponseHandler() {
#Override
public void onSuccess(int statusCode, String content) {
dismiss();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setMessage(R.string.updated_successfully);
builder.setPositiveButton(R.string.ok_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (measureData != null) {
mMeasureList.set(pos, measureData);
tooteet.setMeasureJson(Measure.getMeasureDetailJSON(mMeasureList));
mTooteetManager.updateMeasureTooteet(tooteet, tooteet.getId());
mActionToSend = ACTION_MEASURE_UPDATE;
if (measureData.getValue() % 1 == 0) {
txtValues.setText("" + (int) measureData.getValue()+ " "+MeasureTypeSelector.getMeasureTypeById(FeedMeasureDetailsActivity.this, measureData.getMeasureTypeId()));
} else {
txtValues.setText("" + measureData.getValue()+ " "+ MeasureTypeSelector
.getMeasureTypeById(FeedMeasureDetailsActivity.this, measureData.getMeasureTypeId()));
}
Log.d("TAG", "measureData.getStartDate(): "+measureData.getStartDate());
if(!TextUtils.isEmpty(measureData.getStartDate()) && !measureData.getStartDate().equalsIgnoreCase("-1")) {
lnrStartLayout.setVisibility(View.VISIBLE);
txtStartDateTime.setText("" + DateConversion.getDateAndTimeWithoutGMT(measureData.getStartDate(), "MMMM dd, yyyy hh:mm a"));
}
else{
lnrStartLayout.setVisibility(View.GONE);
}
Log.d("TAG", "measureData.getEndDate(): "+measureData.getEndDate());
if(!TextUtils.isEmpty(measureData.getEndDate())&& !measureData.getStartDate().equalsIgnoreCase("-1")) {
lnrEndLayout.setVisibility(View.VISIBLE);
txtEndDateTime.setText("" + DateConversion.getDateAndTimeWithoutGMT(measureData.getEndDate(), "MMMM dd, yyyy hh:mm a"));
}else{
lnrEndLayout.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measureData.getDescription())){
lnrDescription.setVisibility(View.VISIBLE);
txtDescription.setText(measureData.getDescription());
}
else{
lnrDescription.setVisibility(View.GONE);
}
}
}
});
builder.create().show();
}
#Override
public void onFailure(int statusCode, String content) {
dismiss();
if (!TextUtils.isEmpty(content)) {
AlertUtils.showAlert(FeedMeasureDetailsActivity.this, content);
}
}
private void dismiss() {
if (pd != null && !isFinishing()) {
pd.dismiss();
}
}
});
}
#Override
public void onCancel() {
}
});
}
});
imgEdit.setTag(position);
imgDelete.setTag(position);
addView(parent);
}
My log inside addMeasureView is below:
adding measure data value ________________11111.0 position __________0
adding measure data value ________________22222.0 position __________1
But when i'm viewing this it in layout as this order
adding measure data value ________________22222.0
adding measure data value ________________11111.0
Please suggest me any idea.
This is my model class I'm using for getValue()
import com.kwypesoft.lanes.create_tooteet.LocalTooteetCreator;
import com.kwypesoft.lanes.utils.DateConversion;
import com.kwypesoft.lanes.utils.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
public class Measure implements Serializable{
// "id": "398627f1-9392-4b3f-8741-903fbcbbd3be",
// "tooteetId": "ab36f69e-a0c8-4f31-aa8d-9b4038a76d57",
// "laneId": "00000000-0000-0000-0000-000000000000",
// "startDate": "2016-04-26T08:00:00",
// "endDate": "2016-04-27T10:00:00",
// "value": 125.6500000000000,
// "measureTypeId": 20
public String id;
public String tooteetId;
public String laneId;
public String startDate;
public String endDate;
public String description;
public double value;
public int measureTypeId;
public boolean isTimeSet;
public Measure() {
}
public Measure(JSONArray jsonArray) {
try {
for(int i =0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
id = jsonObject.optString("id");
tooteetId = jsonObject.optString("tooteetId");
laneId = jsonObject.optString("laneId");
startDate = jsonObject.optString("startDate");
endDate = jsonObject.optString("endDate");
description = jsonObject.optString("text");
value = jsonObject.optDouble("value");
measureTypeId = jsonObject.optInt("measureTypeId");
isTimeSet = jsonObject.optBoolean("isTimeSet");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String getMeasureJSON(ArrayList<LocalTooteetCreator.MeasureData> data) {
JSONArray jsonArray = new JSONArray();
for (LocalTooteetCreator.MeasureData items : data) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", items.value);
jsonObject.put("text", items.description);
jsonObject.put("measureTypeId", items.measureTypeId);
if(items.startDate != -1){
jsonObject.put("startDate", DateConversion.getDateWithTFromMilliSeconds(items.startTime, items.startDate));
}
if(items.endDate != -1){
jsonObject.put("endDate", DateConversion.getDateWithTFromMilliSeconds(items.endTime, items.endDate));
}
jsonObject.put("isTimeSet", items.isTimeSet);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
public static String getMeasureDetailJSON(ArrayList<Measure> data) {
JSONArray jsonArray = new JSONArray();
for (Measure items : data) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", items.id);
jsonObject.put("tooteetId", items.tooteetId);
jsonObject.put("laneId", items.laneId);
if(!TextUtils.isEmpty(items.startDate) && !items.getStartDate().equalsIgnoreCase("-1")){
jsonObject.put("startDate", items.startDate);
}
if(!TextUtils.isEmpty(items.endDate) && !items.getStartDate().equalsIgnoreCase("-1")){
jsonObject.put("endDate", items.endDate);
}
jsonObject.put("text", items.description);
jsonObject.put("value", items.value);
jsonObject.put("measureTypeId", items.measureTypeId);
jsonObject.put("isTimeSet", items.isTimeSet);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
public String getId() {
return id;
}
public String getTooteetId() {
return tooteetId;
}
public String getLaneId() {
return laneId;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public double getValue() {
return value;
}
public int getMeasureTypeId() {
return measureTypeId;
}
public boolean getIsTimeSet() {
return isTimeSet;
}
public String getDescription() {
return description;
}
public boolean isTimeSet() {
return isTimeSet;
}
}
Hi I have done a mistake in addview method. Before my addview method is
mDisplayContainer.addView(view, mDisplayContainer.getChildCount() - 1);
Now i changed
mDisplayContainer.addView(view);
Its Working for me. Thank u so much for your comments
I have 3 list in my fragment i.e. list 1,list2 and list3. And all are interdependent.I'm using AsyncTask for showing these list.
When i click on list 1 its shows some data on list 3 and so on when i clik on list 2 it shows data on list3.
Now the problem is there is a next button,if i don't click on list 2 and press next it does not show the correct data.
list 2 returns null and thus does not functional correct.
Below is the code
public class Browse extends Fragment {
ActionBar actionBar;
ListView listView1, listView2, listView3;
ArrayList<String> englishList = new ArrayList<String>();
ArrayList<String> hindiList = new ArrayList<String>();
ArrayList<String> alist1 = new ArrayList<String>();
ArrayList<String> alist2 = new ArrayList<String>();
String response, reply;
TextView tv2;
Browse_Adapter ListAdapter, ListAdapter1;
Browse_Adapter2 adpter2;
LinearLayout linera_t_Layout_1;
boolean result = false;
TextView prev, next;
int pageno = 0, epp;
String txt;
protected String resourceType;
String s;
Context context;
File dbFile1_,dbFile2_,dbFile;
ProgressDialog loadingDialog;
public String DB1 = "sk1.db";
public String DB2 = "sk2.db";
String global,list1_global="a";
Boolean list_flag;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.browse, container, false);
actionBar=getActivity().getActionBar();
MainActivity.state="browse";
context=getActivity().getBaseContext();
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
actionBar.setTitle(getResources().getString(R.string.browse_en));
} else {
actionBar.setTitle(getResources().getString(R.string.browse_hi));
}
/* PREVIOUS AND NEXT TEXTVIEWS CLICKLISTENERS */
prev = (TextView) rootView.findViewById(R.id.prev);
next = (TextView) rootView.findViewById(R.id.next);
// listView 1
listView1 = (ListView) rootView.findViewById(R.id.listView1);
// listView 2
listView2 = (ListView) rootView.findViewById(R.id.listView2);
// listView 3
listView3 = (ListView) rootView.findViewById(R.id.listView3);
listView1.setChoiceMode(1);
listView2.setChoiceMode(1);
listView3.setChoiceMode(1);
View view = inflater.inflate(R.layout.browse, null);
resourceType = (String) view.getTag();
if (resourceType.equals("large")) {
epp = 25;
} else if (resourceType.equals("normal"))
{
epp = 17;
} else if (resourceType.equals("small"))
{
epp = 12;
}
if (!InternetConnection.isInternetOn(context))
{
s= Environment.getExternalStorageDirectory() .toString();
dbFile1_ = new File(s,"sk1.db");
if(!filter.accept(dbFile1_)){
final AlertDialog.Builder alertbox = new AlertDialog.Builder(getActivity());
alertbox.setTitle("Shabdkosh Dictionary");
alertbox.setMessage("Internet connection is not available.");
alertbox.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
alertbox.show();
}
else{
listView1.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text);
if (alist1.size() > 0) {
alist1.clear();
}
if (alist2.size() > 0) {
alist2.clear();
}
prev.setVisibility(View.GONE);
pageno = 0;
textView.setBackgroundColor(getResources().getColor(R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setBackgroundColor(getResources().getColor(
R.color.White));
}
}, DELAY);
txt = textView.getText().toString();
list_flag=true;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs(getActivity()).execute();
//new brs_wd(getActivity(),pageno,list1_global).execute();
} else {
new brs(getActivity()).execute();
//new brs_wd(getActivity(),pageno,list1_global).execute();
}
}
});
}
}
else{
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text);
if (alist1.size() > 0) {
alist1.clear();
}
if (alist2.size() > 0) {
alist2.clear();
}
prev.setVisibility(View.GONE);
pageno = 0;
textView.setBackgroundColor(getResources().getColor(R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setBackgroundColor(getResources().getColor(
R.color.White));
}
}, DELAY);
txt = textView.getText().toString();
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
list_flag=true;//
new brs(getActivity()).execute();
} else {
new brs(getActivity()).execute();
}
}
});
}
prev.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
list_flag=false;
prev.setTextColor((getResources().getColor(R.color.more_changed)));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
prev.setTextColor((getResources().getColor(R.color.text_color)));
}
}, DELAY);
if (alist2.size() > 0) {
alist2.clear();
}
if (pageno > 0) {
pageno = pageno - 1;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,global).execute();
} else {
new brs_wd(getActivity(),pageno,global).execute();
}
}
else {
prev.setVisibility(View.GONE);
}
}
});
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
list_flag=false;//
next.setTextColor((getResources().getColor(R.color.more_changed)));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
next.setTextColor((getResources().getColor(R.color.text_color)));
}
}, DELAY);
prev.setVisibility(View.VISIBLE);
prev.setText("<<Prev");
if (alist2.size() > 0) {
alist2.clear();
}
pageno = pageno + 1;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,global).execute();
} else {
new brs_wd(getActivity(),pageno,global).execute();
}
}
});
englishList.addAll(Arrays.asList("A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z"));
hindiList.addAll(Arrays.asList("अ", "आ", "इ", "ई", "उ", "ऊ", "à¤", "à¤",
"ओ", "औ", "अà¤", "आà¤", "ऋ", "क", "ख", "ग", "घ", "ङ", "च", "छ",
"ज", "à¤", "ञ", "ट", "ठ", "ड", "ढ", "ण", "त", "थ", "द", "ध",
"न", "प", "फ", "ब", "à¤", "म", "य", "र", "ल", "व", "श", "ष",
"स", "ह", "कà¥à¤·" , "तà¥à¤°","जà¥à¤ž"));
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{try{
Browse_Adapter listAdapter1 = new Browse_Adapter(context,
R.layout.browse_list_item, englishList);
if(listAdapter1!=null)
listView1.setAdapter(listAdapter1);}
catch(Exception e){e.printStackTrace();}
} else {
Browse_Adapter listAdapter1 = new Browse_Adapter(context,
R.layout.browse_list_item, hindiList);
if(listAdapter1!=null)
listView1.setAdapter(listAdapter1);
}
listView2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,long id)
{
String item = (String)parent.getItemAtPosition(pos);
global=item;
if (alist2.size() > 0)
{
alist2.clear();
}
pageno = 0;
final TextView textView = (TextView) view
.findViewById(R.id.text_browsword);
textView.setTextColor(getResources().getColor(
R.color.text_color));
int DELAY = 200;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
textView.setTextColor(getResources().getColor(
R.color.White));
}
}, DELAY);
//list1_global=alist1.get(0);
list_flag=false;
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US")) {
new brs_wd(getActivity(),pageno,item).execute();
} else {
new brs_wd(getActivity(),pageno,item).execute();
}
}
});
listView3.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
final TextView textView = (TextView) view
.findViewById(R.id.text_browsword);
if (InternetConnection.isInternetOn(context)) {
SearchData_DTO.setSearchData_DTO(new SearchData()
.getSearched(textView.getText().toString(),
context));
} else {
SearchData_DTO.setSearchData_DTO(new SearchDataDB()
.getSearchedDB(textView.getText().toString(),
context));
}
Intent i = new Intent(context, Search.class);
i.putExtra("selected", textView.getText().toString().replace("(m)", "").replace("(f)", "") .replace("(n)", ""));
startActivity(i);
}
});
setHasOptionsMenu(true);
return rootView;
}
public void onPrepareOptionsMenu(Menu menu)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
menu.removeItem(R.id.English);
menu.removeItem(R.id.Gujarati);
menu.removeItem(R.id.Punjabi);
menu.removeItem(R.id.Bengali);
menu.removeItem(R.id.Marathi);
menu.removeItem(R.id.Talugu);
menu.removeItem(R.id.Tamil);
} else
{
menu.removeItem(R.id.Hindi);
menu.removeItem(R.id.Gujarati);
menu.removeItem(R.id.Punjabi);
menu.removeItem(R.id.Bengali);
menu.removeItem(R.id.Marathi);
menu.removeItem(R.id.Talugu);
menu.removeItem(R.id.Tamil);
}
return;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
item.collapseActionView();
if (R.id.Hindi == item.getItemId()) {
android.support.v4.app.FragmentManager fragmentManager = getChildFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new Browse());
fragmentTransaction.commit();
}
if (R.id.English == item.getItemId()) {
android.support.v4.app.FragmentManager fragmentManager = getChildFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new Browse());
fragmentTransaction.commit();
}
return super.onOptionsItemSelected(item);
}
public boolean browseLetter(final String query, final Context context,final String lang, final String tl)
{
if (InternetConnection.isInternetOn(context))
{
try {
response = CustomHttpClient.executeHttpGet(BROWSE_URL+ "sl=" + lang + "&tl=" + tl+ "&t=1&epp=0&p=1&e=" + query);
if (response != null) {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
alist1.add(arr.getString(i));
}
result = true;
Log.v("--------list1----------", alist1.toString());
}
} catch (Exception e) {
Log.e("/////////////////////////Exception in LIST1 ", e.toString());
}
return true;
} else
{
if (!InternetConnection.isInternetOn(context)) {
s = Environment.getExternalStorageDirectory().toString();
dbFile1_ = new File(s, "sk1.db");
dbFile2_ = new File(s, "sk2.db");
if(dbFile1_.exists()||dbFile2_.exists())
{
/* do something */
alist1 = new ArrayList<String>(new SearchDataDB().ltwo(context,query, lang));
}
else
{
final AlertDialog.Builder alertbox = new AlertDialog.Builder(getActivity());
alertbox.setTitle("Error");
alertbox.setMessage("Internet connection is not available.");
alertbox.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
alertbox.show();
}
}
try{
Browse_Adapter2 listAdapter2 = new Browse_Adapter2(context,R.layout.browse_list_item, alist1);
if(listAdapter2!=null)
listView2.setAdapter(listAdapter2);
result = true;
}
catch(Exception e){e.printStackTrace();}
}
return result;
}
public String browseWord(final String query, final Context context,final String lang, final String tl, final int epp, final int p,String letter)
{
if (InternetConnection.isInternetOn(context))
{
try {
response = CustomHttpClient.executeHttpGet(BROWSE_WORD+ "sl=" + lang + "&tl=" + tl + "&t=2&epp="+ epp + "&p=" + p + "&e=" + query);//
if (response != null) {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
alist2.add(arr.getString(i));
}
}
} catch (Exception e)
{
Log.e("/////////////////////////Exception in LIST2 ", e.toString());
}
return response;
} else {
if (!InternetConnection.isInternetOn(context))
{
alist2 = new ArrayList<String>(new SearchDataDB().bword(context, query, lang));
try{
Browse_Adapter2 listAdapter3 = new Browse_Adapter2(context,R.layout.browse_list_item, alist2);
if(listAdapter3!=null)
listView3.setAdapter(listAdapter3);}
catch(Exception e)
{
e.printStackTrace();
}
txt = query;
if (alist2.size() < epp) {
next.setText("");
}
if (pageno == 0)
prev.setVisibility(View.GONE);
}
}
return response;
}
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File pathname) {
if(pathname.isFile()){
return true;
}
else{
return false;
}
}
};
class brs extends AsyncTask<Object ,Object ,Object >
{
//context=getActivity().getBaseContext();
Activity context;
public brs(Activity context)
{
loadingDialog = new ProgressDialog(context);
this.context=context;
}
#Override
protected void onPreExecute()
{
//loadingDialog= new ProgressDialog(getActivity().getBaseContext());
loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
loadingDialog.setMessage("Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.show();
super.onPreExecute();
};
#Override
protected Object doInBackground(Object... params)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
return browseLetter(txt,context, "en", "hi");
}
else
{
return browseLetter(txt,context, "hi", "en");
}
}
protected void onPostExecute(Object result)
{
try{
if(alist1!=null)
{
//list1_global=alist1.get(0);
Log.v("---------------list1--------------", "list1"+alist1);
Browse_Adapter2 listAdapter2 = new Browse_Adapter2(context,R.layout.browse_list_item, alist1);
if(listAdapter2!=null)
listView2.setAdapter(listAdapter2);}
else{
Log.v("--------------list1--------------", "list1"+alist1);
}
//loadingDialog.dismiss();
}
catch(Exception e)
{
e.printStackTrace();
}
new brs_wd(getActivity(),pageno,list1_global).execute();
//loadingDialog.dismiss();
}
}
class brs_wd extends AsyncTask<Object ,Object ,String>
{
int pg;
Activity context;
String list2word;
public brs_wd(Activity context,int page_no,String list2word)
{
//loadingDialog = new ProgressDialog(context);
this.context=context;
this.pg=page_no;
if(list_flag)
{
this.list2word=txt;
}
else{
this.list2word=list2word;
}
}
#Override
protected void onPreExecute()
{
/*//loadingDialog= new ProgressDialog(getActivity().getBaseContext());
loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
loadingDialog.setMessage("Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.show();*/
super.onPreExecute();
};
#Override
protected String doInBackground(Object... params)
{
if (Locale.getDefault().toString().equalsIgnoreCase("en")||Locale.getDefault().toString().equalsIgnoreCase("en_IN")||Locale.getDefault().toString().equalsIgnoreCase("en_US"))
{
return browseWord(list2word, context, "en", "hi", epp, pg,list2word);
}
else
{
return browseWord(list2word, context, "hi", "en", epp, pg,list2word);
}
}
protected void onPostExecute(String query)
{
try{
Log.d("-------------List2--------", alist2+"");
if(alist2!=null){
Browse_Adapter2 listAdapter3 = new Browse_Adapter2(context, R.layout.browse_list_item, alist2);
if(listAdapter3!=null)
listView3.setAdapter(listAdapter3);
txt = query;
if (alist2.size() < epp) {
next.setText("");
} else {
next.setText("Next>>");
}
if (pageno == 0)
prev.setVisibility(View.GONE);}
else{
Log.d("-------------------List2--------------", "empty"+alist2);
}
}
catch(Exception e)
{
e.printStackTrace();
}
loadingDialog.dismiss();
}
}
}
help me for this.