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
Related
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
I used PagerAdapter for sliding images and i added a favorite button too in that sliding image. After clicking favorite button its not getting notified properly image not turns to unfavorite icon.
it is for loading api
private class PremiumProjectLoad extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url= ApiLinks.PremiumProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(getActivity(),null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("cityID",CommonStrings.cityID);
if(session.isLoggedIn()){
params.put("userID",UserLogin.get(SessionManager.KEY_CUSTOMER_ID));
}
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String Status=json.optString("status");
String Message=json.optString("message");
CommonImagePath=json.optString("imagepath");
PremiumDataArray.clear();
if(Status.equals("ok")){
JSONArray DataArray=json.optJSONArray("data");
if(DataArray!=null && DataArray.length()>0) {
for (int i = 0; i < DataArray.length(); i++) {
JSONObject DataObj = DataArray.optJSONObject(i);
String projectID = DataObj.optString("projectID");
String projectName = DataObj.optString("projectName");
String propertyUnitPriceRange = DataObj.optString("propertyUnitPriceRange");
String projectOfMonthImage = DataObj.optString("projectOfMonthImage");
String propertyUnitBedRooms = DataObj.optString("propertyUnitBedRooms");
String projectBuilderName = DataObj.optString("projectBuilderName");
String propertyTypeName = DataObj.optString("propertyTypeName");
String purpose = DataObj.optString("purpose");
String projectBuilderAddress = DataObj.optString("projectBuilderAddress");
String projectFavourite = DataObj.optString("projectFavourite");
PremiumData premiumData = new PremiumData();
premiumData.setProjectID(projectID);
premiumData.setProjectName(projectName);
premiumData.setPropertyUnitPriceRange(propertyUnitPriceRange);
premiumData.setProjectOfMonthImage(projectOfMonthImage);
premiumData.setPropertyUnitBedRooms(propertyUnitBedRooms);
premiumData.setProjectBuilderName(projectBuilderName);
premiumData.setPropertyTypeName(propertyTypeName);
premiumData.setPurpose(purpose);
premiumData.setProjectBuilderAddress(projectBuilderAddress);
premiumData.setProjectFavourite(projectFavourite);
PremiumDataArray.add(premiumData);
}
LoopViewPager viewpager = (LoopViewPager) homeView.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) homeView.findViewById(R.id.indicator);
// if(pagerAdapter==null)
pagerAdapter = new PremiumProjectAdapter(getActivity(), PremiumDataArray);
viewpager.setAdapter(pagerAdapter);
indicator.setViewPager(viewpager);
// pagerAdapter.notifyDataSetChanged();
}
}
else {
Toast.makeText(getActivity(),Message, Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
pager adapter
public class PremiumProjectAdapter extends PagerAdapter {
private final Random random = new Random();
private ArrayList<PremiumData> mSize;
Context mContext;
LayoutInflater mLayoutInflater;
String ProjectID;
String path=CommonImagePath+"/uploads/projectOfMonth/orginal/";
// public PremiumProjectAdapter() {
// }
public PremiumProjectAdapter(Context contexts, ArrayList<PremiumData> count) {
mSize = count;
mContext=contexts;
}
#Override public int getCount() {
return mSize.size();
}
#Override public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override public void destroyItem(ViewGroup view, int position, Object object) {
view.removeView((View) object);
}
#Override public Object instantiateItem(ViewGroup view, final int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.home_premium_layout, view, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.premium_ProImage);
TextView ProjectName = (TextView) itemView.findViewById(R.id.premium_ProName);
TextView ProjectUnitPrice = (TextView) itemView.findViewById(R.id.premium_UnitPrice);
TextView ProjectUnitBedroom = (TextView) itemView.findViewById(R.id.premium_UnitBedrooms);
TextView ProjectAddress = (TextView) itemView.findViewById(R.id.premium_ProAddress);
ImageView unshortlisted = (ImageView) itemView.findViewById(R.id.unshortlisted);
ImageView shortlisted = (ImageView) itemView.findViewById(R.id.shortlisted);
final PremiumData data = mSize.get(position);
if (data.getProjectFavourite() != null) {
if (data.getProjectFavourite().equals("ShortListed")) {
shortlisted.setVisibility(View.VISIBLE);
unshortlisted.setVisibility(View.GONE);
} else {
shortlisted.setVisibility(View.GONE);
unshortlisted.setVisibility(View.VISIBLE);
}
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange(), Html.FROM_HTML_MODE_COMPACT));
}else{
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange()));
}
ImageLoader.getInstance().displayImage(path+data.getProjectOfMonthImage(), imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(!data.getProjectName().equals("null") && data.getProjectName().length()>30){
String s = data.getProjectName().substring(0, 25);
String subString = s + "...";
ProjectName.setText(subString);
}
else{
ProjectName.setText(data.getProjectName());
}
ProjectUnitBedroom.setText(data.getPropertyUnitBedRooms());
ProjectAddress.setText(data.getProjectBuilderAddress());
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent DetailsAction=new Intent(mContext, DetailsActivity.class);
DetailsAction.putExtra("projectID",data.getProjectID());
DetailsAction.putExtra("purpose",data.getPurpose());
mContext.startActivity(DetailsAction);
}
});
unshortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!session.isLoggedIn()){
Intent toLogin=new Intent(mContext, LoginActivity.class);
CommonStrings.FromSearchIndex="true";
mContext.startActivity(toLogin);
}else{
ProjectID=data.getProjectID();
new ShortlistProject().execute();
}
}
});
shortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProjectID=data.getProjectID();
new UnShortlistProject().execute();
}
});
view.addView(itemView);
return itemView;
}
private class ShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.AddShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
//SearchFragment.getInstance().onResume();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
private class UnShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.RemoveShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
// HomeFragment.getInstance().async_Premium();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
As far as i am able to understand your question you want favorite and unfavorite functionality by adapter . Please use this code below to achieve that :
public class CustomGridAdapterFoodDrink extends BaseAdapter {
private Context mContext;
private ProgressDialog loading;
ArrayList<FoodDrink> foodDrinkArrayList = new ArrayList<>();
SharedPreferences pref;
String userId;
String like_dislike_value = "Like";
String likeValueStr = "1";
boolean like = true;
int positionVal = 444;
HashMap<Integer,Boolean> state = new HashMap<>();
public CustomGridAdapterFoodDrink(Context c, ArrayList<FoodDrink> foodDrinkArrayList) {
mContext = c;
this.foodDrinkArrayList = foodDrinkArrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return foodDrinkArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView projectNamtTxtView = (TextView) grid.findViewById(R.id.projectName);
TextView totalOfferText = (TextView) grid.findViewById(R.id.TotalOffers);
ImageView merchantImage = (ImageView) grid.findViewById(R.id.merchantImage);
final ImageView like_dislike_icon = (ImageView) grid.findViewById(R.id.like_dislike_icon);
totalOfferText.setText(foodDrinkArrayList.get(position).getOffers());
projectNamtTxtView.setText(foodDrinkArrayList.get(position).getProject_name());
Glide.with(mContext)
.load(foodDrinkArrayList.get(position).getProject_photo())
.centerCrop()
.placeholder(R.drawable.review_pro_pic1)
.crossFade()
.into(merchantImage);
like_dislike_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
userId = pref.getString("userId", null);
/* if(state.size()> 0){
like = state.get(position);*/
if (!like) {
like = true;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
} else {
like = false;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it);
likeDislike2(foodDrinkArrayList.get(position).getID(), "0");
}
/* } else {
like = true;
state.put(position,like);
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
}*/
// if(positionVal !=position) {
// likeValueStr ="1";
// positionVal = position;
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
// else {
// likeValueStr ="0";
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
}
});
} else {
grid = (View) convertView;
}
return grid;
}
private void likeDislike(String merchantId, final String like_dislike, final ImageView imageView) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
if (msg.equalsIgnoreCase("Like")) {
imageView.setImageResource(R.mipmap.like_it_act);
} else {
imageView.setImageResource(R.mipmap.like_it);
}
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
private String getlikeUrl(String userId, String merchantId, String like_dislike) {
String url = "";
try {
url = NetworkURL.URL
+ "likeMerchant"
+ "?user_id=" + URLEncoder.encode(new Global().checkNull(userId), "UTF-8")
+ "&merchant_id=" + URLEncoder.encode(new Global().checkNull(merchantId), "UTF-8")
+ "&like_dislike=" + URLEncoder.encode(new Global().checkNull(like_dislike), "UTF-8")
;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
return url;
}
private void likeDislike2(String merchantId, final String like_dislike) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
}
How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.
I am trying to obtain some data from Parse.com through an AsyncTaskRunner. ANd then I intend to show them in a ListView. My custom adapter code is attached below :
public class ParseObjectAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflater;
List<ParseObject> parseArray;
DBShoppingHelper mydb2;
public ParseObjectAdapter(Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
parseArray = new ArrayList<>();
}
#Override
public int getCount() {
try {
return parseArray.size();
}
catch (Exception e){
return 0;
}
}
#Override
public ParseObject getItem(int position) { return parseArray.get(position); }
#Override
public long getItemId(int position) {
return position;
}
public String getObjectId(int position){
return getItem(position).getObjectId();
}
public void sortByExpiry()
{
Comparator<ParseObject> comparator = new Comparator<ParseObject>() {
#Override
public int compare(ParseObject lhs, ParseObject rhs) {
return ((Integer) lhs.getInt("expiresIn")).compareTo(rhs.getInt("expiresIn"));
}
};
Collections.sort(parseArray, comparator);
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder;
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.list_item, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.itemNameView = (TextView) convertView.findViewById(R.id.item_name);
holder.itemExpiryView = (TextView) convertView.findViewById(R.id.item_expiry);
// Taking care of the buttons
holder.editButton = (Button) convertView.findViewById(R.id.button_edit);
holder.deleteButton = (Button) convertView.findViewById(R.id.button_delete);
holder.shoppingListButton = (Button) convertView.findViewById(R.id.button_shopping);
// hang onto this holder for future recycling
convertView.setTag(holder);
int expiry = getItem(position).getInt("expiresIn");
if (expiry <= 0) {
holder.itemExpiryView.setTextColor(Color.rgb(255,80,54));
}
// Set listener on the buttons
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Edit Button CLicked", Toast.LENGTH_SHORT).show();
ParseObject p = getItem(position);
Intent goToAddItem = new Intent(mContext,ItemAddPage.class);
goToAddItem.putExtra("catg_passed", p.getString("category"));
goToAddItem.putExtra("update_flag", "YES");
goToAddItem.putExtra("name passed", p.getString("itemName"));
goToAddItem.putExtra("expires_in_passed", p.getString("expiresIn"));
goToAddItem.putExtra("price_passed", p.getString("itemPrice"));
mContext.startActivity(goToAddItem);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject p = getItem(position);
String android_id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
ParseQuery itemToBeDeleted = new ParseQuery("Items");
itemToBeDeleted.whereEqualTo("ACL", p.getACL());
itemToBeDeleted.whereEqualTo("objectId", p.getObjectId());
final Date deletionDate = new Date();
itemToBeDeleted.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, com.parse.ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
if (Items.size() == 1) {
ParseObject itemToDelete = Items.get(0);
itemToDelete.put("deleted", true);
itemToDelete.put("deletedOn", deletionDate);
itemToDelete.saveEventually();
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
parseArray.remove(p);
sortByExpiry();
notifyDataSetChanged();
Toast.makeText(mContext, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
holder.shoppingListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
ParseObject p = getItem(position);
String add_to_list = p.getString("itemName");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String add_date = sdf.format(new Date());
System.out.println(add_date);
mydb2.insertItem(add_to_list, add_date);
Toast.makeText(mContext, "Item added to shopping list", Toast.LENGTH_SHORT).show();
}
});
ParseObject p = getItem(position);
String name2 = p.getString("itemName");
Integer ex = p.getInt("expiresIn");
String days_s ="";
if (ex == 0) {
days_s = "Expires today" ;
}
else if (ex == -1) {
days_s = "Expired yesterday";
}
else if (ex < 0) {
days_s = "Expired " + Math.abs(ex) + " days ago";
}
else if (ex == 1) {
days_s = "Expires tomorrow";
}
else {
days_s = "Expires in " + ex + " days";
}
holder.itemNameView.setText(name2);
holder.itemExpiryView.setText(days_s);
return convertView;
}
public void onClick(View v)
{
Intent viewItem = new Intent(v.getContext(), ItemAddPage.class);
v.getContext().startActivity(viewItem);
}
private static class ViewHolder {
public TextView itemNameView;
public TextView itemExpiryView;
public Button editButton;
public Button deleteButton;
public Button shoppingListButton;
}
public void updateData(List<ParseObject> arrayPassed) {
// update the adapter's data set
parseArray = arrayPassed;
notifyDataSetChanged();
}
}
This is the method from which I am calling it..
public class WelcomeParse extends Activity {
ListView currentListView;
List<ParseObject> currentList;
ParseObjectAdapter itemAdder;
String catg;
DBShoppingHelper mydb2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
setTheme(android.R.style.Theme_Holo_Light_DarkActionBar);
setContentView(R.layout.activity_main);
itemAdder = new ParseObjectAdapter(this, getLayoutInflater());
mydb2 = new DBShoppingHelper(this);
AsyncTaskAllItems runner = new AsyncTaskAllItems();
runner.execute();
// itemAdder.notifyDataSetChanged();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public class AsyncTaskAllItems extends AsyncTask<String, String, String> {
private String resp;
private Integer numItems = 0;
#Override
protected String doInBackground(String... params) {
try {
ParseQuery itemsAll = new ParseQuery("Items");
itemsAll.whereEqualTo("owner", ParseUser.getCurrentUser().getUsername());
// itemsByCategory.whereEqualTo("category", catg);
itemsAll.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
Log.d("owner", ParseUser.getCurrentUser().getUsername());
// HERE SIZE is 0 then 'No Data Found!'
numItems = Items.size();
if (numItems > 0) {
currentList = Items;
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
resp = "Done";
}
// catch (InterruptedException e) {
// e.printStackTrace();
// resp = e.getMessage();
// }
catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
}
I do not get any error and the log correctly shows the number of items that should be retrieved. But the view does not get updated with the relevant data.
COuld anyone please show me where I am wrong? Anything else you need, just let me know. Much appreciated.
Try after replacing
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
With
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
currentListView.setAdapter(itemAdder);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
}
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.