why MessageAdapter.getData()' on a null object reference - android

I trying to change chatroom.java's createReplayMsg message resource from GCM ,but why apapter.getData().add error?
It tell me java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference.
maybe I should use AsyncTask to finish it?
PS. I am first use this forum ,other Resources in this-> https://github.com/yyting/yoyotrip or tell me,thanks.
Logcat:
09-17 16:42:14.410 8416-8416/com.example.yoyotrip E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.yoyotrip, PID: 8416
java.lang.RuntimeException: Unable to start receiver com.example.yoyotrip.GCM.GcmBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2586)
at android.app.ActivityThread.access$1700(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference
at com.example.yoyotrip.GCM.GcmBroadcastReceiver.onReceive(GcmBroadcastReceiver.java:63)
chatroom.java
package com.example.yoyotrip;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.Toast;
import com.example.yoyotrip.chat.Message;
import com.example.yoyotrip.chat.MessageAdapter;
import com.example.yoyotrip.chat.MessageInputToolBox;
import com.example.yoyotrip.chat.OnOperationListener;
import com.example.yoyotrip.chat.Option;
public class chatroom extends ActionBarActivity {
private MessageInputToolBox box;
public ListView listView;
public MessageAdapter adapter;
public List<Message> messages ;
#SuppressLint("UseSparseArrays")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatroom);
initMessageInputToolBox();
initListView();
}
/**
* init MessageInputToolBox
*/
#SuppressLint("ShowToast")
public void initMessageInputToolBox(){
box = (MessageInputToolBox) findViewById(R.id.messageInputToolBox);
box.setOnOperationListener(new OnOperationListener() {
#Override
public void send(String content) {
System.out.println("===============" + content);
int rd=(int)(Math.random()*99)+1;
Message message = new Message(0, 1, rd%2==1?"Tom":"helen", "avatar", "Jerry", "avatar", content, true, true, new Date());
adapter.getData().add(message);
listView.setSelection(listView.getBottom());
//Just demo
createReplayMsg(message);
}
#Override
public void selectedFace(String content) {
System.out.println("===============" + content);
Message message = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS, "Tomcat", "avatar", "Jerry", "avatar", content, true, true, new Date());
adapter.getData().add(message);
listView.setSelection(listView.getBottom());
//Just demo
createReplayMsg(message);
}
#Override
public void selectedFuncation(int index) {
System.out.println("===============" + index);
switch (index) {
case 0:
//do some thing
break;
case 1:
//do some thing
break;
default:
break;
}
Toast.makeText(chatroom.this, "Do some thing here, index :" +index, Toast.LENGTH_LONG).show();
}
});
ArrayList<String> faceNameList = new ArrayList<String>();
for(int x = 1; x <= 10; x++){
faceNameList.add("big"+x);
}
for(int x = 1; x <= 10; x++){
faceNameList.add("big"+x);
}
ArrayList<String> faceNameList1 = new ArrayList<String>();
for(int x = 1; x <= 7; x++){
faceNameList1.add("cig"+x);
}
ArrayList<String> faceNameList2 = new ArrayList<String>();
for(int x = 1; x <= 24; x++){
faceNameList2.add("dig"+x);
}
Map<Integer, ArrayList<String>> faceData = new HashMap<>();
faceData.put(R.drawable.em_cate_magic, faceNameList2);
faceData.put(R.drawable.em_cate_rib, faceNameList1);
faceData.put(R.drawable.em_cate_duck, faceNameList);
box.setFaceData(faceData);
List<Option> functionData = new ArrayList<Option>();
for(int x = 0; x < 5; x++){
Option takePhotoOption = new Option(this, "Take", R.drawable.take_photo);
Option galleryOption = new Option(this, "Gallery", R.drawable.gallery);
functionData.add(galleryOption);
functionData.add(takePhotoOption);
}
box.setFunctionData(functionData);
}
private void initListView(){
listView = (ListView) findViewById(R.id.messageListview);
//create Data
Message message = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "Hi,大家好我是你們的導遊", true, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 8));
Message message1 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "Hello", false ,true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)* 8));
Message message2 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "helen", "avatar", "Jerry", "avatar", "我們要在哪集合??", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 7));
Message message3 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "台北車站嗎!?", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 7));
Message message4 = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS, "Joe", "avatar", "Jerry", "avatar", "big3", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
Message message5 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Joe", "avatar", "Jerry", "avatar", "可以在229公園那邊嗎?", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
// Message message6 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_FAIL, "Tom", "avatar", "Jerry", "avatar", "test send fail", true, false, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
// Message message7 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SENDING, "Tom", "avatar", "Jerry", "avatar", "test sending", true, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
messages = new ArrayList<Message>();
messages.add(message);
messages.add(message1);
messages.add(message2);
messages.add(message3);
messages.add(message4);
messages.add(message5);
// messages.add(message6);
// messages.add(message7);
adapter = new MessageAdapter(this, messages);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
box.hide();
return false;
}
});
}
//change message resource from GCM
public void createReplayMsg(final Message message){
final Message reMessage = new Message(message.getType(), 1, message.getFromUserName(), "avatar", "Jerry", "avatar",
message.getType() == 0 ? "Re:" + message.getContent() : message.getContent(),
false, true, new Date()
);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000 * (new Random().nextInt(3) +1));
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.getData().add(reMessage);
adapter.notifyDataSetChanged();
listView.setSelection(listView.getBottom());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
MessageAdapter.java
package com.example.yoyotrip.chat;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.example.yoyotrip.R;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
//import com.nostra13.universalimageloader.core.DisplayImageOptions;
//import com.nostra13.universalimageloader.core.ImageLoader;
public class MessageAdapter extends BaseAdapter {
private Context context;
private List<Message> data = null;
public MessageAdapter(Context context, List<Message> list) {
super();
this.context = context;
this.data = list;
}
#Override
public int getCount() {
return data != null ? data.size() : 0;
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return this.data.get(position).getIsSend() ? 1 : 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
final Message message = data.get(position);
boolean isSend = message.getIsSend();
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
if (isSend) {
convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_right, null);
} else {
convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_left, null);
}
viewHolder.sendDateTextView = (TextView) convertView.findViewById(R.id.sendDateTextView);
viewHolder.sendTimeTextView = (TextView) convertView.findViewById(R.id.sendTimeTextView);
viewHolder.userAvatarImageView = (ImageView) convertView.findViewById(R.id.userAvatarImageView);
viewHolder.userNameTextView = (TextView) convertView.findViewById(R.id.userNameTextView);
viewHolder.textTextView = (TextView) convertView.findViewById(R.id.textTextView);
viewHolder.photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
viewHolder.faceImageView = (ImageView) convertView.findViewById(R.id.faceImageView);
viewHolder.failImageView = (ImageView) convertView.findViewById(R.id.failImageView);
viewHolder.sendingProgressBar = (ProgressBar) convertView.findViewById(R.id.sendingProgressBar);
viewHolder.isSend = isSend;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try {
String dateString = DateFormat.format("yyyy-MM-dd h:mmaa", message.getTime()).toString();
String[] t = dateString.split(" ");
viewHolder.sendDateTextView.setText(t[0]);
viewHolder.sendTimeTextView.setText(t[1]);
if(position == 0){
viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
}else{
//TODO is same day ?
Message pmsg = data.get(position-1);
if(inSameDay(pmsg.getTime(), message.getTime())){
viewHolder.sendDateTextView.setVisibility(View.GONE);
}else{
viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
}
}
} catch (Exception e) {
}
viewHolder.userNameTextView.setText(message.getFromUserName());
switch (message.getType()) {
case 0://text
viewHolder.textTextView.setText(message.getContent());
viewHolder.textTextView.setVisibility(View.VISIBLE);
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.GONE);
if(message.getIsSend()){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.textTextView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.textTextView);
if( message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
viewHolder.sendingProgressBar.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.textTextView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
case 1://photo
viewHolder.textTextView.setVisibility(View.GONE);
viewHolder.photoImageView.setVisibility(View.VISIBLE);
viewHolder.faceImageView.setVisibility(View.GONE);
//TODO set image
int id = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
viewHolder.photoImageView.setImageResource(id);
if(message.getIsSend() ){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.photoImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.photoImageView);
if(message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.photoImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
case 2://face
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.textTextView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.VISIBLE);
int resId = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
viewHolder.faceImageView.setImageResource(resId);
if(message.getIsSend()){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.faceImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.faceImageView);
if(message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.faceImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
default:
viewHolder.textTextView.setText(message.getContent());
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.GONE);
break;
}
// viewHolder.textTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
return convertView;
}
public List<Message> getData() {
return data;
}
public void setData(List<Message> data) {
this.data = data;
}
public static boolean inSameDay(Date date1, Date Date2) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int year1 = calendar.get(Calendar.YEAR);
int day1 = calendar.get(Calendar.DAY_OF_YEAR);
calendar.setTime(Date2);
int year2 = calendar.get(Calendar.YEAR);
int day2 = calendar.get(Calendar.DAY_OF_YEAR);
if ((year1 == year2) && (day1 == day2)) {
return true;
}
return false;
}
static class ViewHolder {
public ImageView userAvatarImageView;
public TextView sendDateTextView;
public TextView userNameTextView;
public TextView textTextView;
public ImageView photoImageView;
public ImageView faceImageView;
public ImageView failImageView;
public TextView sendTimeTextView;
public ProgressBar sendingProgressBar;
public boolean isSend = true;
}
}
GcmBroadcastReceiver.java
package com.example.yoyotrip.GCM;
/**
* Created by colm on 2015/8/3.
*/
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.widget.ListView;
import com.example.yoyotrip.MainActivity;
import com.example.yoyotrip.R;
import com.example.yoyotrip.chat.Message;
import com.example.yoyotrip.chat.MessageAdapter;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.util.Date;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
public static final int NOTIFICATION_ID = 0;
public ListView listView;
public MessageAdapter adapter;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
Log.i(getClass() + " GCM ERROR", extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
Log.i(getClass() + " GCM DELETE", extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
Log.i(getClass() + " GCM MESSAGE", extras.toString());
if (extras.getString("title") .equals("chat")) {
/*show noteic*/
Intent i = new Intent(context, MainActivity.class);
i.setAction("android.intent.action.MAIN");
i.addCategory("android.intent.category.LAUNCHER");
MagicLenGCM.sendLocalNotification(context, NOTIFICATION_ID,
R.drawable.icon, "noteic", extras
.getString("message"), extras.getString("whofrom"), false,
PendingIntent.getActivity(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT));
//message addchat
final Message message = new Message(0, 1, extras.getString("whofrom"), "avatar", "Jerry", "avatar", extras.getString("message"), false, true, new Date());
adapter.getData().add(message);
adapter.notifyDataSetChanged();
listView.setSelection(listView.getBottom());
} else if (extras.getString("title").equals("GCM")) {
Intent i = new Intent(context, MainActivity.class);
i.setAction("android.intent.action.MAIN");
i.addCategory("android.intent.category.LAUNCHER");
MagicLenGCM.sendLocalNotification(context, NOTIFICATION_ID,
R.drawable.icon, "GCM noteic", extras
.getString("message"), "yoyotrip", false,
PendingIntent.getActivity(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT));
}
}
}
setResultCode(Activity.RESULT_OK);
}
}

You never use your adapter's constructor to create a new instance in GcmBroadcastReceiver. Your adapter will always be null, hence, NullPointerExceptions on that getData() call.

Related

How do I get the quantity from every item in cart and pass to an activity?

i have a cartactivity and cartadapter, in cartadapter i add increment and decrement for each stuff, and i sum it in total price and total weight and send it to activity ( it worked by passing textview activity from cartactivity to adapteractivity ) and now i want to get seperated quantity for each item to send to database with format Example if item is ( Wallet, Bag, Shoes ) then quanitity that will send to database like this ( 2, 3, 3) 2 represent for wallet and (,) for seperating item quantity, 3 represent bag, and 3 represent shoes. i don't know how to take each quantity and send it in a format like that
have a look on my adapter
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import app.gify.co.id.R;
import app.gify.co.id.activity.List_Kado;
import app.gify.co.id.modal.MadolCart;
public class AdapterCart extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<MadolCart> carts;
MadolCart mm;
View view;
View viewku;
Context context;
int kuantitas;
String totalname;
int totalBerat, totalharga;
TextView totalhargas, totalberats;
public AdapterCart(ArrayList<MadolCart> carts, Context context, TextView totalhargas, TextView totalberats) {
this.carts = carts;
this.context = context;
this.totalhargas = totalhargas;
this.totalberats = totalberats;
}
public class MyCart extends RecyclerView.ViewHolder {
public ImageView gambar, tambah, kurang;
public TextView harga, nama, quantitas;
public RelativeLayout background, foreground;
public ElegantNumberButton quantity;
public MyCart(#NonNull View itemView) {
super(itemView);
gambar = itemView.findViewById(R.id.gambarcart);
tambah = itemView.findViewById(R.id.tambahcart);
kurang = itemView.findViewById(R.id.kurangcart);
harga = itemView.findViewById(R.id.hargacart);
nama = itemView.findViewById(R.id.namacart);
quantitas = itemView.findViewById(R.id.quantitas);
background = itemView.findViewById(R.id.background);
foreground = itemView.findViewById(R.id.foreground);
quantity = itemView.findViewById(R.id.quantity);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_cart, parent, false);
viewku = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart, parent, false);
return new MyCart(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
kuantitas = carts.get(position).getJumlah();
int hargaku = carts.get(position).getHarga() * kuantitas;
for (int a = 0; a < carts.size(); a++){
Log.d("cartsizeku", "onBindViewHolder: " + carts.size()+ " s " + carts.get(a).getNamacart() + " s " + carts.get(a).getHarga());
String nama = carts.get(position).getNamacart();
if (nama.equals(carts.get(a).getNamacart())){
totalhargas.setText(String.valueOf(totalCart(carts, carts.get(a).getNamacart())));
totalberats.setText(String.valueOf(beratCart(carts, carts.get(a).getNamacart())));
}
}
Locale locale = new Locale("id", "ID");
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
((MyCart)holder).harga.setText(format.format(Double.valueOf(hargaku)));
((MyCart)holder).nama.setText(carts.get(position).getNamacart());
Glide.with(view).load(carts.get(position).getGambar()).into(((MyCart)holder).gambar);
Intent intent = new Intent("message_subject_intent");
// intent.putExtra("name", String.valueOf((totalCart(carts))));
intent.putExtra("title", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
((MyCart) holder).tambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = Integer.parseInt(((MyCart) holder).quantitas.getText().toString());
if (count<9){
count+=1;
((MyCart)holder).quantitas.setText(String.valueOf(count));
int harga = carts.get(position).getHarga()*count;
((MyCart)holder).harga.setText(String.valueOf(format.format(Double.valueOf(harga))));
String nama = carts.get(position).getNamacart();
totalhargas.setText(String.valueOf(totalCart(carts, nama)));
totalberats.setText(String.valueOf(beratCart(carts, nama)));
}
// ((MyCart)holder).quantitas.setText(String.valueOf(kuantitas));
int total = hargaku * kuantitas;
Intent intents = new Intent("message_subject_intent");
intents.putExtra("name", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intents);
}
});
((MyCart) holder).kurang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = Integer.parseInt(((MyCart)holder).quantitas.getText().toString());
if (count>1){
count-=1;
((MyCart)holder).quantitas.setText(String.valueOf(count));
int harga = carts.get(position).getHarga()*count;
((MyCart)holder).harga.setText(String.valueOf(format.format(Double.valueOf(harga))));
String nama = carts.get(position).getNamacart();
totalhargas.setText(String.valueOf(kurangtotalcart(carts, nama)));
totalberats.setText(String.valueOf(kurangberatCart(carts, nama)));
}
// ((MyCart)holder).quantitas.setText(String.valueOf(kuantitas));
int total = hargaku * kuantitas;
Intent intents = new Intent("message_subject_intent");
intents.putExtra("name", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intents);
}
});
}
#Override
public int getItemCount() {
return carts.size();
}
public int totalCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga += items.get(i).getHarga();
}
}
return totalharga;
}
public int kurangtotalcart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga -= items.get(i).getHarga();
}
}
return totalharga;
}
public int beratCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalBerat += items.get(i).getBerat();
}
}
return totalBerat;
}
public int kurangberatCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalBerat -= items.get(i).getBerat();
}
}
return totalBerat;
}
public String getName(List<MadolCart> name){
String ku = "";
for (int i = 0; i < name.size(); i++){
ku += name.get(i).getNamacart() + ", ";
}
return ku;
}
public void removeItem(int item){
carts.remove(item);
notifyItemRemoved(item);
}
public void restoreItem(MadolCart madolCart, int item){
carts.add(item, madolCart);
notifyItemInserted(item);
}
public void quantityPlus(MadolCart madolCart, int item){
}
}
and this is my activity
package app.gify.co.id.activity;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.DrawableImageViewTarget;
import com.google.android.material.navigation.NavigationView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Locale;
import java.util.Random;
import app.gify.co.id.R;
import app.gify.co.id.adapter.AdapterCart;
import app.gify.co.id.modal.MadolCart;
//import app.gify.co.id.thirdparty.GMailSender;
//import app.gify.co.id.thirdparty.SenderAgent;
import app.gify.co.id.widgets.RecyclerTouchDelete;
import static app.gify.co.id.baseurl.UrlJson.DELETECART;
import static app.gify.co.id.baseurl.UrlJson.GETBARANG;
import static app.gify.co.id.baseurl.UrlJson.GETCART;
public class CartActivity extends AppCompatActivity implements RecyclerTouchDelete.RecyclerTouchListener{
Button Checkout, lanjutBelanja;
ImageView backCart;
TextView totalbelanjar, totalberat;
AdapterCart adapterCart;
ArrayList<MadolCart> madolCarts;
String namacart, gambarcart, uidku;
GridLayoutManager glm;
RecyclerView recyclerView;
MainActivity mainActivity;
NavigationView navigationView;
public int hargaku, beratku, kuantitas, lastNumber, idbarang, getHargaAwal;
SharedPreferences preferences;
SharedPreferences.Editor editor;
Spanned templateConvert;
NumberFormat format;
Locale id;
Random random;
String template, idberat, idharga;
private Dialog dialog;
LayoutInflater inflater;
ImageView goku;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart);
lanjutBelanja = findViewById(R.id.lanjutBelanjaChart);
lanjutBelanja.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), List_Kado.class);
startActivity(intent);
});
getHargaAwal = getIntent().getIntExtra("harga", 0);
Log.d("setHarga", getHargaAwal + "");
dialog = new Dialog(CartActivity.this);
inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.loading, null);
goku = layout.findViewById(R.id.custom_loading_imageView);
goku.animate().rotationBy(360).setDuration(3000).setInterpolator(new LinearInterpolator()).start();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.setCancelable(false);
dialog.setContentView(layout);
dialog.show();
id = new Locale("id", "ID");
format = NumberFormat.getCurrencyInstance(id);
random = new Random();
lastNumber = 0;
for (int k = 0; k < 3; k++){
lastNumber+=(random.nextInt(10)*Math.pow(10, k));
}
backCart = findViewById(R.id.backCartNav);
backCart.setOnClickListener(v -> finish());
Checkout = findViewById(R.id.checkoutChart);
totalbelanjar = findViewById(R.id.totalBelanjaChart);
totalberat = findViewById(R.id.totalBeratChart);
recyclerView = findViewById(R.id.rvChart);
preferences = PreferenceManager.getDefaultSharedPreferences(CartActivity.this);
uidku = preferences.getString("uid", "");
madolCarts = new ArrayList<>();
getCart();
glm = new GridLayoutManager(CartActivity.this, 1);
recyclerView.setLayoutManager(glm);
Checkout.setOnClickListener(view -> {
Intent intent = new Intent(CartActivity.this, CheckoutActivity.class);
intent.putExtra("idharga", idharga);
intent.putExtra("name", namacart);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = preferences.edit();
editor.remove("range");
editor.remove("acara");
editor.remove("buat");
editor.apply();
startActivity(intent);
});
LocalBroadcastManager.getInstance(this).registerReceiver(passValue, new IntentFilter("message_subject_intent"));
ItemTouchHelper.SimpleCallback callback = new RecyclerTouchDelete(0, ItemTouchHelper.LEFT, this);
new ItemTouchHelper(callback).attachToRecyclerView(recyclerView);
}
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
private String replaceNumberOfAmount(String original, int replace){
return original.substring(0, original.length() - 3) + replace;
}
// private void senderEmail(){
// SenderAgent senderAgent = new SenderAgent("gify.firebase#gmail.com", "Confirmation Transaction Gify", templateConvert, CartActivity.this);
// senderAgent.execute();
// }
private void getCart(){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETCART, null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
String id_tetap = object.getString("id_tetap");
if (id_tetap.equalsIgnoreCase(uidku)){
kuantitas = object.getInt("jumlah");
idbarang = object.getInt("id_barang");
idharga = object.getString("harga");
idberat = object.getString("berat");
getBerat(idbarang);
dialog.dismiss();
}
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
Log.d("getcart", "getCart: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
public BroadcastReceiver passValue = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
namacart = intent.getStringExtra("name");
Log.d("hargalast", namacart + "");
namacart = intent.getStringExtra("title");
template = "<h2> Gify Transaction </h2> " +
"<h3> Kamu baru saja melakukan pesanan dengan detail sebagai berikut </h3>"
+ "<p><b> Nama barang: </p></b>"
+ "<p><b> Harga barang" + format.format(Double.valueOf(replaceNumberOfAmount(idharga, lastNumber))) + ". Silahkan transfer dengan tiga digit terakhir yaitu :" + lastNumber + "</p></b>"
+ "<p><b> Jika sudah melakukan pembayaran, silahkan konfirmasi disini </p></b>"
+ "https://api.whatsapp.com/send?phone=082325328732&text=Confirmation%20Text"
+ "<h2>Salam, Gify Team</h2>";
Log.d("hargalast", idharga + lastNumber);
templateConvert = Html.fromHtml(template);
}
};
private void getBerat(int idbarang){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETBARANG, null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
int id_barang = object.getInt("id");
if (idbarang==id_barang){
String gambar = object.getString("photo");
int harga = object.getInt("harga");
String namacart = object.getString("nama");
int berat = object.getInt("berat");
MadolCart madolCart = new MadolCart(gambar, harga, namacart, idbarang, kuantitas, berat);
madolCarts.add(madolCart);
adapterCart = new AdapterCart(madolCarts, CartActivity.this, totalbelanjar, totalberat);
recyclerView.setAdapter(adapterCart);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
Log.d("jsoner", "getBerat: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
#Override
public void onSwipe(RecyclerView.ViewHolder viewHolder, int dir, int pos) {
if (viewHolder instanceof AdapterCart.MyCart){
String name = madolCarts.get(viewHolder.getAdapterPosition()).getNamacart();
MadolCart madolCart = madolCarts.get(viewHolder.getAdapterPosition());
int deleteIndex = viewHolder.getAdapterPosition();
Log.d("taptap", "onSwipe: " + madolCarts.get(viewHolder.getAdapterPosition()).getNamacart());
GETBARANG(madolCarts.get(viewHolder.getAdapterPosition()).getNamacart());
adapterCart.removeItem(viewHolder.getAdapterPosition());
}
}
private void deletecart(String id_barang){
StringRequest stringRequest = new StringRequest(Request.Method.GET, DELETECART+"?idtetap="+uidku+"&idbarang="+id_barang, response -> {
try {
if (response.equalsIgnoreCase("bisa")){
Toast.makeText(CartActivity.this, "Barang telah di hapus", Toast.LENGTH_SHORT).show();
Log.d("bisabarangcart", "GETBARANG: " );
}
}catch (Exception e){
Log.d("ekscartactivity", "deletecart: " + e.getMessage());
}
}, error -> {
Log.d("ernocartdel", "deletecart: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(stringRequest);
}
private void GETBARANG(String namas){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETBARANG,null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
String nama = object.getString("nama");
if (nama.equalsIgnoreCase(namas)){
Log.d("namabarang", "GETBARANG: " + nama + " s " + namas);
String id = object.getString("id");
deletecart(id);
}
}
}catch (Exception e){
Log.d("barangexce", "GETBARANG: " + e.getMessage());
}
}, error -> {
Log.d("errorgetbrng", "GETBARANG: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
}
to make sum of total prices i used this code
public int totalCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga += items.get(i).getHarga();
}
}
return totalharga;
}
i put summing code in a method, and call the method on if button + is clicked
if button - is clicked it will call this method
public int kurangtotalcart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga -= items.get(i).getHarga();
}
}
return totalharga;
}
and now idk how to get seperated quanitity for each position / item in recycler view then send it to activity as format ( 1, 2, 3) (,) mean a seperator for each item
How to get value seperated quantity from recycler view item position?
SOLVED
public String getSeperatedquantity(List<MadolCart> quantity){
String kus = "";
for (int i = 0; i < quantity.size(); i++){
kus += quantity.get(i).getQuantity() + ", ";
}
return kus;
}
I found the solution by adding this:
public String getSeperatedquantity(List<MadolCart> quantity){
String kus = "";
for (int i = 0; i < quantity.size(); i++){
kus += quantity.get(i).getQuantity() + ", ";
}
return kus;
}

Open a actvity when a if statement comes true

Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);

ProgressDialog.show() is not showing the progress dialog

I am trying to display a progress dialog inside a fragment.But progressbar.show() do not have any effect.However,I noticed a strange behaviour,if i call showPopUp() method twice,it does show the progress dialog,but unable to dismiss().
package com.snapbizz.snapdashboard.Tabs.v1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.snapbizz.snapdashboard.Core.v1.SalesData;
import com.snapbizz.snapdashboard.R;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DashBoardSalesTab extends Fragment {
LinearLayout salesListContainer, salesBarConatainer;
LayoutInflater layoutInflater;
SalesData salesData;
ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sales_page_layout, container, false);
return rootView;
}
public void showPopUp() {
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("loading the page...");
progressDialog.setProgressNumberFormat(null);
progressDialog.setProgressPercentFormat(null);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
public void synchronizeScrollers() {
getActivity().findViewById(R.id.page_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
getActivity().findViewById(R.id.table_scroller).getParent()
.requestDisallowInterceptTouchEvent(true);
return false;
}
});
getActivity().findViewById(R.id.table_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
public void renderSalesGraph(List<String[]> values, Float totalSumY) throws Exception {
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0] + " " + date[1]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[2]);
salesBarConatainer.addView(barView);
}
}
public void renderSalesGraphForMonths(List<String[]> values, Float totalSumY) throws Exception {
LinearLayout salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, renderingDate.getMonth());
cal.set(Calendar.DAY_OF_MONTH, 1);
barView.setOnClickListener(new MonthBarClickListener(cal));
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[1]);
salesBarConatainer.addView(barView);
}
}
public String[] addTOSalesTable(String date, boolean header) throws Exception {
List<String[]> values = salesData.getSalesTableData(date);
String[] value = values.get(0);
String[] newValue = {value[0], value[1], date};
String totalSales = (value[0] == null) ? "0" : value[0];
String totalCredit = (value[1] == null) ? "0" : value[1];
String totalCash = (Float.parseFloat(totalSales) - Float.parseFloat(totalCredit)) + "";
String rupeeSymbol = getActivity().getResources().getString(R.string.rupee_symbol);
if (!header) {
View salesRow = layoutInflater.inflate(R.layout.sales_page_table_row_layout, salesListContainer, false);
((TextView) (salesRow.findViewById(R.id.sale_date))).
setText(date);
((TextView) (salesRow.findViewById(R.id.sales_total_sale))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (salesRow.findViewById(R.id.sales_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (salesRow.findViewById(R.id.sales_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (salesRow.findViewById(R.id.sales_ttoal_coupon))).
setText(rupeeSymbol + " " + "0");
if (salesListContainer.getChildCount() % 2 != 0) {
salesRow.setBackgroundColor(getResources().getColor(R.color.table_row_alternate_color));
}
salesListContainer.addView(salesRow);
} else {
((TextView) (getActivity().findViewById(R.id.sales_header_total_sales))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (getActivity().findViewById(R.id.sales_header_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (getActivity().findViewById(R.id.sales_header_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (getActivity().findViewById(R.id.sales_header_total_coupon))).
setText(rupeeSymbol + " " + "0");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date presentDate = new Date();
((TextView) (getActivity().findViewById(R.id.sales_header_day))).
setText(date.contentEquals(dateFormat.format(presentDate)) ? "Today" : date);
}
return newValue;
}
public void getMonths() throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
List<String[]> values = new ArrayList<>();
float totalSumY = 0.0f;
for (int i = 0; i < 12; i++) {
cal.add(Calendar.MONTH, (i == 0) ? 0 : -1);
String date = dateFormat.format(cal.getTime());
String[] value = salesData.getSalesDataForMonth(date);
String[] newValue = {value[0] == null ? "0" : value[0], value[1] == null ? "0" : value[1], date};
totalSumY += Float.parseFloat(value[0] == null ? "0" : value[0]);
values.add(newValue);
}
renderSalesGraphForMonths(values, totalSumY);
}
public void initChart() {
FrameLayout dayButton = (FrameLayout) getActivity().findViewById(R.id.day_button);
FrameLayout monthButton = (FrameLayout) getActivity().findViewById(R.id.month_button);
dayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
monthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
getMonths();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void generateTablesRows(Calendar cal, int limit, int increment) throws Exception {
salesListContainer.removeAllViews();
float totalSumY = 0.0f;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
List<String[]> barGraphValues = new ArrayList<>();
for (int i = 0; i < limit; i++) {
cal.add(Calendar.DATE, (i == 0) ? 0 : increment);
String date = dateFormat.format(cal.getTime());
String[] value = addTOSalesTable(date, (i == 0) ? true : false);
totalSumY += Float.parseFloat((value[0] == null) ? "1" : value[0]);
barGraphValues.add(value);
}
renderSalesGraph(barGraphValues, totalSumY);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
showPopUp();
layoutInflater = LayoutInflater.from(getContext());
salesListContainer = (LinearLayout) (getActivity().findViewById(R.id.sales_list_container));
salesListContainer.removeAllViews();
salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
new SalesTabLoader().execute();
}
public class MonthBarClickListener implements View.OnClickListener {
Calendar cal;
public MonthBarClickListener(Calendar cal) {
this.cal = cal;
}
#Override
public void onClick(View v) {
try {
//new SalesAsyncTask(cal).execute(cal.getActualMaximum(Calendar.DAY_OF_MONTH),1);
generateTablesRows(cal, cal.getActualMaximum(Calendar.DAY_OF_MONTH), 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class SalesTabLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
salesData = new SalesData(getContext());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
initChart();
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
} finally {
synchronizeScrollers();
progressDialog.dismiss();
}
}
}
}
Try like this :
progressDialog = new ProgressDialog(getActivity());
And if you wish to customize your dialog and put self created Layout in it.
/**
* Created by vivek on 18/10/16.
*/
public class CustomDialog {
private static Dialog dialog;
private static Context context;
public CustomDialog(Context context) {
this.context = context;
}
/**
* Comman progress dialog ... initiates with this
*
* #param message
* #param title
*/
public static void showProgressDialog(Context context, String title, String message) {
if (dialog == null)
{
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loader);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
public static boolean isProgressDialogRunning() {
if (dialog != null && dialog.isShowing()) {
return true;
} else return false;
}
/**
* Dismiss comman progress dialog
*/
public static void dismissProgressDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}
} // End of main class over here ...
Replace this:-
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
with
progressDialog = new ProgressDialog(getActivity());
May be. you are showing two progressdialog and both of that progressbar on screen.. but when you dismiss your progressbar at that time the previous one is override by other one before you dismiss first one .. so the firstone is always in screen. that's the issue.
I tried everything.But none of the answers solved the issue.However,i solved it by overriding onResume() method in the fragment.
Thanks All.

android : Badge not remove from calendar

I am creating calendar which contains events and I want to show total no of events on particular date. I am using
CalendarAdapter.java class. For showing total no. of events count (like notification bubble) on date I am using
Badge.java class. Now problem is that badge is apply on Calendars dates which current month is showing first,
after changing month then that badge is not remove from next month calendar.
Calendar Adapter:
package vyClean.wemecalendar.adapters;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import vyClean.wemecalendar.activity.Event1;
import vyClean.wemecalendar.util.BadgeView;
import vyClean.wemecalendar.util.BadgeView1;
import vyClean.wemecalendar.util.CalendarEvent;
import vyClean.wemecalendar.R;
import vyClean.wemecalendar.util.ToastMessage;
public class CalendarAdapter extends BaseAdapter {
private Context context;
private java.util.Calendar month;
public GregorianCalendar pmonth;
/*-----------calendar instance for previous month for getting complete view-------------------*/
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
public static TextView textno;
RelativeLayout cal_item_ll;
private ArrayList<String> items;
public static List<String> day_string;
private View previousView;
private View getView;
public ArrayList<CalendarEvent> event_calendar_arr;
public CalendarAdapter(Context context, GregorianCalendar monthCalendar, ArrayList<CalendarEvent> event_calendar_arr) {
this.event_calendar_arr = event_calendar_arr;
CalendarAdapter.day_string = new ArrayList<>();
Locale.setDefault(Locale.getDefault());
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
this.context = context;
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public int getCount() {
return day_string.size();
}
public Object getItem(int position) {
return day_string.get(position);
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
getView = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getView = vi.inflate(R.layout.cal_item, parent, false);
cal_item_ll = (RelativeLayout) getView.findViewById(R.id.cal_item_ll);
//textno = (TextView) getView.findViewById(R.id.textno);
}
dayView = (TextView) getView.findViewById(R.id.date);
String[] separatedTime = day_string.get(position).split("-");
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
dayView.setTextColor(Color.GRAY);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.GRAY);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.parseColor("#ff69b4"));
}
if (day_string.get(position).equals(curentDateString)) {
getView.setBackgroundColor(Color.CYAN);
} else {
getView.setBackgroundColor(Color.WHITE);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = day_string.get(position);
if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}
int len = CalendarEvent.event_calendar_arr.size();
HashSet<String> eventListSet1 = new HashSet<>();
int flag = 0;
for (int j = 0; j < len; j++) {
//textno.setTextColor(Color.WHITE);
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(j);
if (day_string.get(position).equals(cal_event.getEventFromDate())) {
eventListSet1.add(cal_event.getEventCateId());
flag = 1;
}
}
if (flag == 1) {
setEventView(getView, position, dayView, eventListSet1);
/*----------call badgeview here--------*/
/*----------call badgeview on linear layout (cal_item_ll) which is inside getview--------*/
BadgeView badge = new BadgeView(context, cal_item_ll);
badge.setText("1");
badge.show();
}
System.out.println("eventListSet1:" + eventListSet1);
return getView;
}
public View setSelected(View view, int pos) {
if (previousView != null) {
// previousView.setBackgroundColor(Color.CYAN);
previousView.setBackgroundColor(Color.WHITE);
}
view = previousView;
// view.setBackgroundColor(Color.CYAN);
int len = day_string.size();
if (len > pos) {
if (day_string.get(pos).equals(curentDateString)) {
} else {
previousView = view;
}
}
return view;
}
public void refreshDays() {
// clear items
items.clear();
day_string.clear();
Locale.setDefault(Locale.getDefault());
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
//Calendar instance for getting a complete gridview including the three month's (previous,current,next) dates.
pmonthmaxset = (GregorianCalendar) pmonth.clone();
//setting the start date as previous month's required date.
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
// filling calendar gridview.
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
System.out.println(" 214 itemvale :" + itemvalue);
day_string.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(GregorianCalendar.MONTH) == month
.getActualMinimum(GregorianCalendar.MONTH)) {
pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
pmonth.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
return maxP;
}
public void setEventView(View v, int pos, TextView txt, HashSet<String> eventListSet1) {
ArrayList<String> eventList = new ArrayList<>();
int len = CalendarEvent.event_calendar_arr.size();
for (int i = 0; i < len; i++) {
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(i);
int len1 = day_string.size();
if (len1 > pos) {
String category = cal_event.getEventCateId();
HashSet<String> eventListSet = new HashSet<String>();
StringTokenizer stR = new StringTokenizer(category, ",");
while (stR.hasMoreTokens()) {
eventListSet.add(stR.nextToken());
}
ArrayList<String> sortedList = new ArrayList(eventListSet1);
Collections.sort(sortedList);
//System.out.println("sortedList:" + sortedList);
StringBuffer CategoryNew = new StringBuffer();
Iterator<String> itr = sortedList.iterator();
while (itr.hasNext()) {
CategoryNew.append(itr.next() + ",");
}
eventList.add(category);
switch (CategoryNew.toString()) {
/* ----------only one category ----------*/
case "1,":
v.setBackgroundResource(R.drawable.gs);
break;
case "2,":
v.setBackgroundResource(R.drawable.se);
break;
case "3,":
v.setBackgroundResource(R.drawable.ge);
break;
case "4,":
v.setBackgroundResource(R.drawable.tuce);
break;
/*----------two category----------*/
case "1,2,":
v.setBackgroundResource(R.drawable.gsse);
break;
case "1,3,":
v.setBackgroundResource(R.drawable.gsge);
break;
case "1,4,":
v.setBackgroundResource(R.drawable.gstuce);
break;
case "2,3,":
v.setBackgroundResource(R.drawable.sege);
break;
case "2,4,":
v.setBackgroundResource(R.drawable.setuce);
break;
case "3,4,":
v.setBackgroundResource(R.drawable.getuce);
break;
/*----------three category----------*/
case "1,2,3,":
v.setBackgroundResource(R.drawable.gssege);
break;
case "1,3,4,":
v.setBackgroundResource(R.drawable.gsgetuce);
break;
case "1,2,4,":
v.setBackgroundResource(R.drawable.gssetuce);
break;
case "2,3,4,":
v.setBackgroundResource(R.drawable.gesetuce);
break;
/*----------four category----------*/
case "1,2,3,4,":
v.setBackgroundResource(R.drawable.gssegetuce);
default:
System.out.println("Invalid event");
break;
}
/*BadgeView1 badge = new BadgeView1(context, cal_item_ll);
badge.setText("1");
badge.show();*/
txt.setTextColor(Color.BLUE);
}
}
}
public void getPositionList(String date, final Activity act) {
final String TAG_EVENT_NAME = "event_name";
final String TAG_EVENT_DESC = "event_desc";
final String TAG_EVENT_FROM_DATE = "event_from_date";
final String TAG_EVENT_TO_DATE = "event_to_date";
final String TAG_EVENT_TIMING = "event_timing";
final String TAG_EVENT_PLACE = "event_place";
final String TAG_EVENT_CATE_ID = "event_cate_id";
String event_name, event_desc, event_from_date;
String event_to_date, event_timing, event_place, event_cate_id;
ArrayList<HashMap<String, String>> event = new ArrayList<>();
int len = CalendarEvent.event_calendar_arr.size();
for (int i = 0; i < len; i++) {
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(i);
event_name = cal_event.getEventName();
event_desc = cal_event.getEventDesc();
event_from_date = cal_event.getEventFromDate();
event_to_date = cal_event.getEventToDate();
event_timing = cal_event.getEventTiming();
event_place = cal_event.getEventPlace();
event_cate_id = cal_event.getEventCateId();
if (date.equals(event_from_date)) {
HashMap<String, String> map = new HashMap<>();
map.put(TAG_EVENT_NAME, event_name);
map.put(TAG_EVENT_DESC, event_desc);
map.put(TAG_EVENT_FROM_DATE, event_from_date);
map.put(TAG_EVENT_TO_DATE, event_to_date);
map.put(TAG_EVENT_TIMING, event_timing);
map.put(TAG_EVENT_PLACE, event_place);
if (event_cate_id.equals(1)) {
map.put(TAG_EVENT_CATE_ID, "General Science");
}
if (event_cate_id.equals(2)) {
map.put(TAG_EVENT_CATE_ID, "Scientific Exhibition");
}
if (event_cate_id.equals(3)) {
map.put(TAG_EVENT_CATE_ID, "General Events");
}
if (event_cate_id.equals(4)) {
map.put(TAG_EVENT_CATE_ID, "Tuce Clubs");
}
if (event_cate_id.equals("")) {
map.put(TAG_EVENT_CATE_ID, "");
}
event.add(map);
}
}
if (event.size() > 0) {
Bundle b = new Bundle();
b.putSerializable("EVENT_LIST", event);
Intent in = new Intent(context, Event1.class);
in.putExtras(b);
context.startActivity(in);
} else {
ToastMessage.toastMessage(context, "On this date there is no event");
}
}
BadgeView.class -
package vyClean.wemecalendar.util;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
public class BadgeView extends TextView {
private Context context;
protected View target;
private ShapeDrawable badgeBg;
public BadgeView(Context context, View target) {
this(context, null, android.R.attr.textViewStyle, target);
}
public BadgeView(Context context, AttributeSet attrs, int defStyle, View target) {
super(context, attrs, defStyle);
init(context, target);
}
private void init(Context context, View target) {
try {
this.context = context;
this.target = target;
//apply defaults
setTypeface(Typeface.DEFAULT_BOLD);
setPadding(7, 0, 7, 0);
setTextColor(Color.WHITE);
if (this.target != null) {
applyTo(this.target);
} else {
show();
}
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
private void applyTo(View target) {
try {
ViewGroup.LayoutParams lp = target.getLayoutParams();
//ViewParent parent = target.getParent();
FrameLayout container = new FrameLayout(context);
// TODO verify that parent is indeed a ViewGroup
ViewGroup group = (ViewGroup) target;
int index = group.indexOfChild(target);
group.removeView(target);
group.addView(container, index,lp);
container.addView(target);
container.addView(this);
group.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void show() {
try {
if (getBackground() == null) {
if (badgeBg == null) {
badgeBg = getDefaultBackground();
}
setBackgroundDrawable(badgeBg);
}
applyLayoutParams();
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
private ShapeDrawable getDefaultBackground() {
ShapeDrawable drawable = null;
try {
float[] outerR = new float[]{20, 20, 20, 20, 20, 20, 20, 20};
RoundRectShape rr = new RoundRectShape(outerR, null, null);
drawable = new ShapeDrawable(rr);
drawable.getPaint().setColor(Color.BLACK);
} catch (StackOverflowError e) {
e.printStackTrace();
}
return drawable;
}
private void applyLayoutParams() {
try {
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.RIGHT | Gravity.TOP;
setLayoutParams(lp);
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
}

Sliding after auto slide on button clicke using ViewPager gives erro in android

I have made a View Pager in that I want to implement manually slide(OnTOuch) and auto slide(onButton Click)..Both functions are working when use alone.But when i slede from one to another image and start auto Slide,It gives me IllegalStateException..And stops..Please help me to solve it,My code is as below:
package com.epe.smaniquines.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Timer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.epe.smaniquines.R;
import com.epe.smaniquines.adapter.SimpleGestureFilter;
import com.epe.smaniquines.backend.AlertDialogManager;
import com.epe.smaniquines.backend.ConnectionDetector;
import com.epe.smaniquines.uc.Menu;
import com.epe.smaniquines.util.Const;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class DetailsActivity extends Activity implements OnClickListener,
OnTouchListener {
private SimpleGestureFilter detector;
ImageView proImage, ivSave, ivInfo, ivPlay, ivBak, iv_share;
RelativeLayout rl_botm, rl_option;
TextView tv_facebuk, tv_twiter, tv_nothanks, tv_email, tv_save, tv_quote;
String big_img;
int pos;
ImagePagerAdapter adapter;
ViewPager viewPager;
private static SharedPreferences mSharedPreferences;
ArrayList<String> resultArray;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
RelativeLayout rl_info;
public boolean flag = false;
Menu menu;
public boolean flag1 = false;
boolean isOnClick = false;
int i = 0;
String cat_nem;
File casted_image;
private int PicPosition;
private Handler handler = new Handler();
ProgressDialog pDialog;
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
int mFlipping = 0;
ViewFlipper viewFlipper;
Timer timer;
int flagD = 0;
String data;
String shareType;
File image;
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
TextView titledetail;
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
public static String PACKAGE_NAME;
static String TWITTER_CONSUMER_KEY = "AzFSBq1Od4lYGGcGR0u9GkMIT"; // place
static String TWITTER_CONSUMER_SECRET = "MBwdard2Y4l6LT6z219NJ6x8aZ4jyK8JBKZ85usRPcDP8ujwM0"; // place
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_detail);
PACKAGE_NAME = getApplicationContext().getPackageName();
initialize();
cat_nem = getIntent().getStringExtra("cat_name");
System.out.println(":::::::::::CAt nem:::::::::" + cat_nem);
titledetail.setText(cat_nem);
proImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
proImage.setOnTouchListener(this);
showHashKey(this);
printKeyHashForThisDevice();
pos = getIntent().getIntExtra("pos", 0);
System.out.println(":::::::::::::::current pos::::::::::" + pos);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/*
* Intent i = getIntent(); data = i.getStringExtra("data"); shareType =
* i.getStringExtra("type");
*/
big_img = getIntent().getStringExtra(Const.TAG_BIG_IMG);
// imageLoader.displayImage(big_img, proImage, options);
resultArray = getIntent().getStringArrayListExtra("array");
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setVisibility(View.VISIBLE);
adapter = new ImagePagerAdapter();
viewPager.setCurrentItem(resultArray.indexOf(pos));
viewPager.setAdapter(adapter);
ivInfo.setOnClickListener(this);
ivPlay.setOnClickListener(this);
tv_email.setOnClickListener(this);
tv_facebuk.setOnClickListener(this);
tv_nothanks.setOnClickListener(this);
tv_save.setOnClickListener(this);
tv_twiter.setOnClickListener(this);
iv_share.setOnClickListener(this);
ivBak.setOnClickListener(this);
tv_quote.setOnClickListener(this);
proImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewPager.setVisibility(View.VISIBLE);
Animation anim;
anim = (Animation) getResources().getAnimation(
R.anim.animated_activity_slide_right_in);
viewPager.setAnimation(anim);
}
});
// viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
/*
* imageLoader.displayImage(big_img, proImage, options);
* proImage.postDelayed(swapImage, 1000);
*/
viewPager.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isOnClick) {
if (event.getX() > viewPager.getWidth() / 2) {
// go to next
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i++;
} else {
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i--;
// go to previous
}
return true;
}
}
return false;
}
});
}
public void open(View view) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello test"); // <- String
Uri screenshotUri = Uri.parse(image.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
void initialize() {
proImage = (ImageView) findViewById(R.id.iv_det);
ivInfo = (ImageView) findViewById(R.id.iv_info);
ivPlay = (ImageView) findViewById(R.id.iv_play);
ivBak = (ImageView) findViewById(R.id.iv_back);
rl_botm = (RelativeLayout) findViewById(R.id.rl_bottom);
rl_option = (RelativeLayout) findViewById(R.id.rl_options);
tv_save = (TextView) findViewById(R.id.tv_save);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_facebuk = (TextView) findViewById(R.id.tv_facebook);
tv_nothanks = (TextView) findViewById(R.id.tv_no_thanks);
tv_twiter = (TextView) findViewById(R.id.tv_twiter);
rl_option.setVisibility(View.GONE);
tv_quote = (TextView) findViewById(R.id.tv_qote);
iv_share = (ImageView) findViewById(R.id.iv_share);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(DetailsActivity.this));
rl_info = (RelativeLayout) findViewById(R.id.rl_info);
rl_info.setVisibility(View.GONE);
resultArray = new ArrayList<String>();
ivPlay.setVisibility(View.VISIBLE);
titledetail = (TextView) findViewById(R.id.titledetail);
// twitter
// Login button
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_share:
rl_option.setVisibility(View.VISIBLE);
rl_info.setVisibility(View.GONE);
if (flag1) {
rl_option.setVisibility(View.VISIBLE);
flag1 = false;
} else {
rl_option.setVisibility(View.GONE);
flag1 = true;
}
break;
case R.id.iv_play:
/*
* proImage.setVisibility(View.GONE);
*
* AdapterViewFlipper flipper = (AdapterViewFlipper)
* findViewById(R.id.flipper); flipper.setAutoStart(true);
* flipper.setAdapter(new FlipperAdapter(DetailsActivity.this,
* resultArray));
*/
i = 0;
final Handler handler = new Handler();
final Runnable ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
if (i <= adapter.getCount() - 1) {
viewPager.setCurrentItem(i, true);
handler.postDelayed(this, 2000);
i++;
}
}
};
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setVisibility(View.INVISIBLE);
break;
case R.id.iv_back:
finish();
break;
case R.id.tv_email:
rl_option.setVisibility(View.GONE);
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL,
new String[] { "youremail#yahoo.com" });
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
break;
case R.id.tv_save:
save();
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_facebook:
// facebookShare();
/*
* save(); open(v);
*/
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_no_thanks:
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_twiter:
rl_option.setVisibility(View.GONE);
// loginToTwitter();
// new updateTwitterStatus().execute("3sManiquines");
break;
case R.id.iv_info:
rl_info.setVisibility(View.VISIBLE);
rl_option.setVisibility(View.GONE);
if (flag) {
rl_info.setVisibility(View.VISIBLE);
flag = false;
} else {
rl_info.setVisibility(View.GONE);
flag = true;
}
break;
case R.id.tv_qote:
rl_option.setVisibility(View.GONE);
String url = big_img;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Hi Go to product for details:");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
i.putExtra(Intent.EXTRA_SUBJECT, "Quote");
i.putExtra(Intent.EXTRA_TEXT, builder);
startActivity(Intent.createChooser(i, "Select application"));
break;
}
}
public static void showHashKey(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
"com.epe.3SManiquines", PackageManager.GET_SIGNATURES); // Your
// package
// name
// here
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.v("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
// slide show..!!!
MediaPlayer introSound, bellSound;
Runnable swapImage = new Runnable() {
#Override
public void run() {
myslideshow();
handler.postDelayed(this, 1000);
}
};
private void myslideshow() {
PicPosition = resultArray.indexOf(big_img);
if (PicPosition >= resultArray.size())
PicPosition = resultArray.indexOf(big_img); // stop
else
resultArray.get(PicPosition);// move to the next gallery element.
}
//
// SAVE TO SD CARD..!!
void save() {
BitmapDrawable drawable = (BitmapDrawable) proImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory.getAbsolutePath()
+ "/3sManiquines/");
image = new File(sdCardDirectory, "3s_" + System.currentTimeMillis()
+ ".png");
dir.mkdirs();
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
addImageToGallery(dir + "", DetailsActivity.this);
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}//
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
// facebook...
private void printKeyHashForThisDevice() {
try {
System.out
.println("::::::::::::::::::::HAsh key called:::::::::::::");
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyHash = Base64.encodeToString(md.digest(),
Base64.DEFAULT);
System.out
.println(":::::::::::KEy hash:::::::::::::" + keyHash);
System.out.println("================KeyHash================ "
+ keyHash);
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
float touchPointX = event.getX();
float touchPointY = event.getY();
int[] coordinates = new int[2];
rl_info.getLocationOnScreen(coordinates);
rl_option.getLocationOnScreen(coordinates);
if (touchPointX < coordinates[0]
|| touchPointX > coordinates[0] + rl_info.getWidth()
|| touchPointY < coordinates[1]
|| touchPointY > coordinates[1] + rl_info.getHeight())
rl_info.setVisibility(View.INVISIBLE);
rl_option.setVisibility(View.INVISIBLE);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
break;
case MotionEvent.ACTION_UP: // first finger lifted
/*
* if (i < resultArray.size()) {
* imageLoader.displayImage(resultArray.get(i), proImage); i++; }
*/
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger down
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
//
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return resultArray.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = DetailsActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageLoader.displayImage(resultArray.get(position), imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
Try it and post output or logcat
private void postInitViewPager() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = viewpager.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
mScroller = new ScrollerCustomDuration(getContext(),
(Interpolator) interpolator.get(null));
Log.d("TAG", "mScroller is: " + mScroller + ", "
+ mScroller.getClass().getSuperclass().getCanonicalName() + "; this class is "
+ this + ", " + getClass().getSuperclass().getCanonicalName());
scroller.set(this, mScroller);
} catch (Exception e) {
Log.e("MyPager", e.getMessage());
}

Categories

Resources