How to properly use a Handler - java

I'm trying to create a tuner app right now and it has two errors, both stemming from Handlers.
public class Pitch extends Fragment {
private static final String TAG = "Pitch";
private TextView tv_pitch;
private TextView tv_note;
View rootView;
Context mContext;
Tuner tn;
private Handler mHandler;
private final static double[] stringFreqs = {82.41, 110.0, 146.83, 196.00, 246.94, 329.63};
private static HashMap<Double, String> stringNames = new HashMap<>();
Tuner.PitchDetectedListener listener = new Tuner.PitchDetectedListener() {
#Override
public void onPitchDetected(double pitch, double amplitude) {
Log.d(TAG, "Pitch: " + pitch + " Amplitude: " + amplitude);
if (amplitude > 1000000.0) {
double doublePitch = pitch * 2;
double halfPitch = pitch / 2;
for (double freq : stringFreqs) {
if (pitch > freq - 3 && pitch < freq + 3) {
Log.d(TAG, stringNames.get(freq) + " with pitch of " + pitch);
display_color(pitch, freq);
return;
}
}
for (double freq : stringFreqs) {
if (doublePitch > freq - 3 && doublePitch < freq + 3) {
Log.d(TAG, stringNames.get(freq) + " with pitch of " + pitch);
display_color(doublePitch, freq);
return;
}
}
for (double freq : stringFreqs) {
if (halfPitch > freq - 3 && halfPitch < freq + 3) {
Log.d(TAG, stringNames.get(freq) + " with pitch of " + pitch);
display_color(halfPitch, freq);
return;
}
}
}
}
};
private void display_color(final double pitch, final double freq) {
mHandler.post(new Runnable() {
#Override
public void run() {
tv_note.setText(stringNames.get(freq));
tv_pitch.setText(Double.toString(pitch));
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_tuner, container, false);
final BoxInsetLayout tuner = (BoxInsetLayout) rootView.findViewById(R.id.tuner_box);
final ImageView start = (ImageView) rootView.findViewById(R.id.tuner);
final ImageView stop = (ImageView) rootView.findViewById(R.id.tuner);
mContext = getActivity().getApplicationContext();
Typeface font = Typeface.createFromAsset(mContext.getAssets(), "fonts/Foglihten-068.otf");
tv_note.setTypeface(font);
tv_note.setText("-");
mHandler = new Handler(getMainLooper());
tv_note = (TextView) rootView.findViewById(R.id.tv_note);
int i = 0;
stringNames.put(stringFreqs[i++], "E");
stringNames.put(stringFreqs[i++], "A");
stringNames.put(stringFreqs[i++], "D");
stringNames.put(stringFreqs[i++], "G");
stringNames.put(stringFreqs[i++], "B");
stringNames.put(stringFreqs[i], "e");
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tn.run();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tn.stop();
}
});
tv_pitch = (TextView) tuner.findViewById(R.id.tv_pitch);
tv_note = (TextView) tuner.findViewById(R.id.tv_note);
return rootView;
tn = new Tuner(listener);
}
public void onPause() {
tn.stop();
super.onPause();
}
}
My errors are in these lines:
mHandler.post(new Runnable() {
mHandler = new Handler(getMainLooper());
The first line results in cannot resolve method 'post(java.lang.Runnable)', and the second line results in cannot resolve method 'getMainLooper.'
Can anyone help figure out what's going wrong?

Check your imports. You accidentally imported java.util.logging.Handler instead of android.os.Handler.
Most of the time you create object where you need a handler on UI thread so you're safe to use this:
private final Handler mHandler = new Handler();
A more general approach will look like this (post to UI thread from other threads):
private final Handler mHandler = new Handler(Looper.getMainLooper());

Related

Dynamic Text view Adroid Game

I wanted to have a textview that will show the money of the player. But
myMoneyTextView.setText(String.valueOf(acc.getMoney))
doesn't update it I need to reopen the intent to see those changes. I want to change it when the player spend or gain money.
EDIT.
private SubsamplingScaleImageView imageView;
private CustomButton up, down, menu, employ, sales, social, schedule, chart, states, mail;
private TextView comMon, comName;
private DataBase db;
Handler handler = new Handler(Looper.getMainLooper());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_screen);
officeRender();
updateGame();
butThread thread = new butThread();
new Thread(thread).start();
comName = findViewById(R.id.companyname);
comMon = findViewById(R.id.money);
}
public void updateGame() {
handler.post(new Runnable() {
#Override
public void run() {
db = new DataBase(GameScreen.this);
Account acc = db.getAcc();
comName.setText(acc.getName() + " Ent.");
String mon = String.valueOf(acc.getMoney());
if (acc.getMoney() < 100000) {
comMon.setText(mon);
}
else if (acc.getMoney() >= 100000) {
comMon.setText(mon.substring(0, 3) + "k");
}
else if (acc.getMoney() >= 1000000) {
comMon.setText(mon.substring(0, 3) + "m");
}
}
});

I can't display the timer in a TextView

I've created a Listview with a Countdown timer and below is the code :
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
long timeLeftMS ;
// View lookup cache
private class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtTempsRestant;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("handler");
int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
int minute = (int) ((timeLeftMS / (60000)) % 60);
int seconde = (int)timeLeftMS % 60000 / 1000;
String timeLeftText = "";
if (hour<10) timeLeftText += "0";
timeLeftText += hour;
timeLeftText += ":";
if (minute<10) timeLeftText += "0";
timeLeftText += minute;
timeLeftText += ":";
if (seconde<10) timeLeftText += "0";
timeLeftText += seconde;
txtTempsRestant.setText(timeLeftText);
}
};
}
public TicketAdapter(ArrayList<TicketModel> data, Context context) {
super(context, R.layout.row_item_ticket, data);
this.dataSet = data;
this.mContext=context;
//startUpdateTimer();
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
TicketModel TicketModel=(TicketModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
TicketModel TicketModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(TicketModel.getTitreTicket());
viewHolder.txtDate.setText(TicketModel.getDateTicket());
viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
//viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct
timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());
startTimer(viewHolder.handler);
// Return the completed view to render on screen
return convertView;
}
private void startTimer(final Handler handler) {
CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {
#Override
public void onTick(long l) {
timeLeftMS = l;
handler.sendEmptyMessage(0);
}
#Override
public void onFinish() {
}
}.start();
}
private int getColorBG(boolean ticketEnRetard) {
int color;
if (ticketEnRetard){
color = Color.parseColor("#3caa0000");
}
else{
color = Color.parseColor("#ffffff");
}
return color;
}
private int getIconUrgence(String urgenceTicket) {
int icon;
if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
icon = R.drawable.basse;
}
else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
icon = R.drawable.haute;
}
else {
icon = R.drawable.moyenne;
}
return icon;
}
}
TicketModel class :
public class TicketModel {
String titreTicket;
String slaTicket;
String DateTicket;
String UrgenceTicket;
boolean ticketEnRetard;
String TempsRestantTicket;
public TicketModel(String titreTicket, String slaTicket, String dateTicket, String tempsRestantTicket) {
this.titreTicket = titreTicket;
this.slaTicket = slaTicket;
DateTicket = dateTicket;
TempsRestantTicket = tempsRestantTicket;
}
public String getTitreTicket() {
return titreTicket;
}
public String getSlaTicket() {
return slaTicket;
}
public String getDateTicket() {
return DateTicket;
}
public String getUrgenceTicket() {
return UrgenceTicket;
}
public void setUrgenceTicket(String urgenceTicket) {
UrgenceTicket = urgenceTicket;
}
public void setTempsRestantTicket(String tempsRestantTicket) {
TempsRestantTicket = tempsRestantTicket;
}
public String getTempsRestantTicket() {
return TempsRestantTicket;
}
public boolean isTicketEnRetard() {
return ticketEnRetard;
}
public void setTicketEnRetard(boolean ticketEnRetard) {
this.ticketEnRetard = ticketEnRetard;
}
}
Where I'm populating my ListView :
public class ListTickets extends AppCompatActivity {
ArrayList<TicketModel> TicketModels;
ListView listView;
private static TicketAdapter adapter;
String session_token, nameUser, idUser, firstnameUser, nbTicket;
RequestQueue queue;
String titreTicket, slaTicket, urgenceTicket,
demandeurTicket, categorieTicket, etatTicket, dateDebutTicket,
dateEchanceTicket, dateClotureTicket, descriptionTicket, lieuTicket;
boolean ticketEnretard;
public static int nbTicketTab = 6;
public static int nbInfoTicket = 12;
public static String[][] ticketTab ;
public static String[][] infoTicket ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
queue = Volley.newRequestQueue(this);
Intent i = getIntent();
session_token = i.getStringExtra("session");
nbTicket = i.getStringExtra("nb");
nameUser = i.getStringExtra("nom");
firstnameUser = i.getStringExtra("prenom");
idUser = i.getStringExtra("id");
listView=(ListView)findViewById(R.id.list);
TicketModels = new ArrayList<>();
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
infoTicket = new String[Integer.valueOf(nbTicket)][nbInfoTicket];
String url = FirstEverActivity.GLPI_URL+"search/Ticket";
List<KeyValuePair> params = new ArrayList<>();
params.add(new KeyValuePair("criteria[0][field]","5"));
params.add(new KeyValuePair("criteria[0][searchtype]","equals"));
params.add(new KeyValuePair("criteria[0][value]",idUser));
params.add(new KeyValuePair("forcedisplay[0]","4"));
params.add(new KeyValuePair("forcedisplay[1]","10"));
params.add(new KeyValuePair("forcedisplay[2]","7"));
params.add(new KeyValuePair("forcedisplay[3]","12"));
params.add(new KeyValuePair("forcedisplay[4]","15"));
params.add(new KeyValuePair("forcedisplay[5]","30"));
params.add(new KeyValuePair("forcedisplay[6]","18"));
params.add(new KeyValuePair("forcedisplay[7]","21"));
params.add(new KeyValuePair("forcedisplay[8]","83"));
params.add(new KeyValuePair("forcedisplay[9]","82"));
params.add(new KeyValuePair("forcedisplay[10]","16"));
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, generateUrl(url, params), null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
// Récupération des items pour le row_item
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
//Récupération du reste
demandeurTicket = oneTicket.getString("4");
categorieTicket = oneTicket.getString("7");
etatTicket = oneTicket.getString("12");
dateEchanceTicket = oneTicket.getString("18");
descriptionTicket = oneTicket.getString("21");
lieuTicket = oneTicket.getString("83");
dateClotureTicket = oneTicket.getString("16");
ticketEnretard = getBooleanFromSt(oneTicket.getString("82"));
System.out.println("Direct = " + oneTicket.getString("82") + "\n After f(x) = " + getBooleanFromSt(oneTicket.getString("82")));
} catch (JSONException e) {
Log.e("Nb of data: "+Jdata.length()+" || "+"Error JSONArray at "+i+" : ", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket); //TimeLeft value here
ticketTab[i][5] = String.valueOf(ticketEnretard);
infoTicket[i][0] = demandeurTicket;
infoTicket[i][1] = urgenceText(urgenceTicket);
infoTicket[i][2] = categorieTicket;
infoTicket[i][3] = etatText(etatTicket);
infoTicket[i][4] = dateDebutTicket;
infoTicket[i][5] = slaTicket;
infoTicket[i][6] = dateEchanceTicket;
infoTicket[i][7] = titreTicket;
infoTicket[i][8] = descriptionTicket;
infoTicket[i][9] = lieuTicket;
infoTicket[i][10] = calculTempsRestant(dateDebutTicket, slaTicket);
infoTicket[i][11] = dateClotureTicket;
System.out.println("Temps restant = "+calculTempsRestant(dateDebutTicket, slaTicket));
System.out.println("SLA = "+slaTicket);
System.out.println("Between : "+getBetweenBrackets(slaTicket));
System.out.println("Minimum : "+getMinTemps(slaTicket));
System.out.println("Maximim : "+getMaxTemps(slaTicket));
}
System.out.println("*** Tab Ticket ***");
System.out.println("isLate: "+ticketTab[0][5]);
System.out.println("\n\n*** Info Ticket ***");
System.out.println("Titre: "+infoTicket[0][7]);
// Populate the ListView
addModelsFromTab(ticketTab);
adapter = new TicketAdapter(TicketModels,getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TicketModel TicketModel= TicketModels.get(position);
Snackbar.make(view, "Index = "+position, Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
Intent i = new Intent(getApplicationContext(), InfoTicket.class);
i.putExtra("session",session_token);
i.putExtra("nom",nameUser);
i.putExtra("prenom",firstnameUser);
i.putExtra("id",idUser);
i.putExtra("infoTicket", infoTicket[position]);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
//progressBar.setVisibility(View.GONE);
Log.e("Error.Response", error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
private void addModelsFromTab(String[][] ticketTab) {
for (int i = 0; i < ticketTab.length; i++){
TicketModel ticket = new TicketModel(ticketTab[i][0], ticketTab[i][1], ticketTab[i][2], ticketTab[i][4]);
ticket.setUrgenceTicket(ticketTab[i][3]);
ticket.setTicketEnRetard(Boolean.parseBoolean(ticketTab[i][5]));
//ticket.setTempsRestantTicket(ticketTab[i][4]);
TicketModels.add(ticket);
}
}
private String calculTempsRestant(String dateDebutTicket, String slaTicket) {
String minTemps = getMinTemps(slaTicket);
String maxTemps = getMaxTemps(slaTicket);
long dateDebutMS = getDateDebutMS(dateDebutTicket);
long currentTimeMS = CurrentTimeMS();
long minTempsMS = hourToMSConvert(minTemps);
long differenceCurrentDebut = currentTimeMS - dateDebutMS;
long tempsRestant = minTempsMS - differenceCurrentDebut;
return String.valueOf(tempsRestant);
}
}
The issue I have is that I want to display the timer (the timeLeftText String) in the txtTempsRestant TextView, but I can't access it. Can anyone give me advice?
When I print in the console and the output is correct, but I'm not able to display it. Should I change the way I'm working?
Modified Adapter class to make the count down work properly.
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
// View lookup cache
private class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtTempsRestant;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("handler");
Bundle bundle = msg.getData();
long timeLeftMS = bundle.getLong("time");
int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
int minute = (int) ((timeLeftMS / (60000)) % 60);
int seconde = (int)timeLeftMS % 60000 / 1000;
String timeLeftText = "";
if (hour<10) timeLeftText += "0";
timeLeftText += hour;
timeLeftText += ":";
if (minute<10) timeLeftText += "0";
timeLeftText += minute;
timeLeftText += ":";
if (seconde<10) timeLeftText += "0";
timeLeftText += seconde;
txtTempsRestant.setText(timeLeftText);
}
};
public void startTimer(long timeLeftMS) {
CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {
#Override
public void onTick(long l) {
Bundle bundle = new Bundle();
bundle.putLong("time", l);
Message message = new Message();
message.setData(bundle);
handler.sendMessage(message);
}
#Override
public void onFinish() {
}
}.start();
}
}
public TicketAdapter(ArrayList<TicketModel> data, Context context) {
super(context, R.layout.row_item_ticket, data);
this.dataSet = data;
this.mContext=context;
//startUpdateTimer();
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
TicketModel TicketModel=(TicketModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
TicketModel TicketModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);
result=convertView;
viewHolder.startTimer(Long.valueOf(TicketModel.getTempsRestantTicket()));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(TicketModel.getTitreTicket());
viewHolder.txtDate.setText(TicketModel.getDateTicket());
viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
//viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct
// Return the completed view to render on screen
return convertView;
}
private int getColorBG(boolean ticketEnRetard) {
int color;
if (ticketEnRetard){
color = Color.parseColor("#3caa0000");
}
else{
color = Color.parseColor("#ffffff");
}
return color;
}
private int getIconUrgence(String urgenceTicket) {
int icon;
if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
icon = R.drawable.basse;
}
else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
icon = R.drawable.haute;
}
else {
icon = R.drawable.moyenne;
}
return icon;
}
}
You don't want to declare the TextView static if you'll be changing the value.
Try declaring it outside the method here:
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
static long timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());
private TextView txtTempsRestant ;
// View lookup cache
private static class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
TextView txtTempsRestant ;
}
Hi i have a code its good
beucse u dont need definination 3 textview for right and left ,....
You will create one TextView and use this code for create
private void Time() {
mCountTimer = new CountDownTimer(aTime, 1000) {
#Override
public void onTick(long millisUntilFinished) {
aMinute = (int) (millisUntilFinished / 1000) / 60;
mSecond = (int) (millisUntilFinished / 1000) % 60;
mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", aMinute, mSecond));
}
#Override
public void onFinish() {
mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", 0, 0));
mSend_Again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your EVENT
}
});
}
}.start();
}

Inserting More than One row into SQLite at a time

I have a cart that can insert only one product at a time, but now i have to insert more than one product at a time. I use check boxes to select the items.
What do I need to change to allow inserting more than one product into the cart?
This is my Adapter Class :
public class AdapterPrice extends BaseAdapter {
ArrayList<ModelPrice> listPrice;
private Context context;
int selectedPosition = 0;
public AdapterPrice(Context context, ArrayList<ModelPrice> listPrice) {
this.context = context;
this.listPrice = listPrice;
}
#Override
public int getCount() {
return listPrice.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
final AdapterPrice.ViewHolder holder;
if (view == null) {
holder = new AdapterPrice.ViewHolder();
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_packing, null);
holder.txtOffer = view.findViewById(R.id.txtOffer);
holder.txtPrice = view.findViewById(R.id.txtPrice);
holder.txtQty = view.findViewById(R.id.txtQty);
//holder.radioWeight = view.findViewById(R.id.radioWeight);
holder.checkBox = view.findViewById(R.id.checkboxWeight);
holder.icMinus = view.findViewById(R.id.icMinus);
holder.icPlus = view.findViewById(R.id.icPlus);
view.setTag(holder);
} else {
holder = (AdapterPrice.ViewHolder) view.getTag();
}
//holder.radioWeight.setText((UtilMethods.decimalFormater(listPrice.get(position).getWeight())) + listPrice.get(position).getUnit());
holder.checkBox.setText((UtilMethods.decimalFormater(listPrice.get(position).getWeight())) + listPrice.get(position).getUnit());
double packMrpd = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
double offerMrpd = (double) listPrice.get(position).getQty() * listPrice.get(position).getSellMrp();
holder.txtPrice.setText("Rs." + UtilMethods.decimalFormater(packMrpd));
holder.txtOffer.setText("Rs." + UtilMethods.decimalFormater(offerMrpd));
holder.txtQty.setText(listPrice.get(position).getQty() + "");
/*holder.radioWeight.setChecked(position == selectedPosition);
holder.radioWeight.setTag(position);*/
holder.checkBox.setChecked(position == selectedPosition);
Log.d("POSITION CB>>>>>>",position+"");
//holder.checkBox.setTag(position);
if (holder.checkBox.isChecked()) {
String forString = "for " + UtilMethods.decimalFormater(listPrice.get(selectedPosition).getWeight()) + "" + listPrice.get(selectedPosition).getUnit();
SpannableString forStr = new SpannableString(forString);
forStr.setSpan(new UnderlineSpan(), 0, forString.length(), 0);
//txtFor.setText(forStr);
//txtOferPrice.setText("Rs." + UtilMethods.decimalFormater(listPrice.get(selectedPosition).getSellMrp()) + "");
double saveMrp = ((double) listPrice.get(position).getQty() * listPrice.get(position).getMrp()) - ((double) listPrice.get(position).getQty() * listPrice.get(position).getSellMrp());
txtSAve.setText("Rs." + (UtilMethods.decimalFormater(saveMrp)) + "");
if (saveMrp <= 0) {
offerLayout.setVisibility(View.GONE);
}
mQty = listPrice.get(position).getQty();
mMrp = listPrice.get(position).getMrp();
mSellMrp = listPrice.get(position).getSellMrp();
mweight = listPrice.get(position).getWeight();
mUnit = listPrice.get(position).getUnit();
seletUnit = (1 * selectedPosition);
}
/*holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
notifyDataSetChanged();
}
});*/
holder.icMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int cQty = listPrice.get(position).getQty();
if (cQty > 1) {
cQty = listPrice.get(position).getQty() - 1;
listPrice.get(position).setQty(cQty);
// double totalMrp = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
//holder.txtPrice.setText((String.format("%.2f", totalMrp)) + "");
/* if (position == selectedPosition) {
double saveMrp = totalMrp - (listPrice.get(selectedPosition).getSellMrp() * (double) listPrice.get(position).getQty());
// txtSAve.setText("Rs."+saveMrp + "");
}*/
notifyDataSetChanged();
}
}
});
holder.icPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int cQty = listPrice.get(position).getQty();
cQty = listPrice.get(position).getQty() + 1;
listPrice.get(position).setQty(cQty);
//double totalMrp = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
// holder.txtPrice.setText((String.format("%.2f", totalMrp)) + "");
/* if (position == selectedPosition) {
double saveMrp = totalMrp - (listPrice.get(selectedPosition).getSellMrp() * (double) listPrice.get(position).getQty());
// txtSAve.setText(saveMrp + "");
}*/
notifyDataSetChanged();
}
});
return view;
}
public class ViewHolder {
private TextView txtPrice, txtQty, txtOffer;
private RadioButton radioWeight;
CheckBox checkBox;
private ImageView icPlus, icMinus;
}
}
this is where i insert item into cart through SQLIte :
private void addToCArt() {
ModelCart mcart = new ModelCart();
mcart.setProductName(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getProductName());
mcart.setPid(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getPid());
mcart.setImageUrl(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getImageTag1());
List<String> attrId = new ArrayList<>();
for (ModelPrice mmp : Config.LIST_SINGAL_PRODUCT.get(tempPosition).getListPrice()) {
attrId.add(mmp.getWid() + "," + mmp.getWeight() + "," + mmp.getUnit());
}
String aData = TextUtils.join("-", attrId);
mcart.setQty(mQty);
mcart.setWeight(mweight);
mcart.setUnit(mUnit);
mcart.setMrp(mMrp);
mcart.setSellMrp(mSellMrp);
mcart.setAttributeData(aData);
mcart.setSelectUnit(seletUnit);
mcart.setSelecAttrId((Config.LIST_SINGAL_PRODUCT.get(tempPosition).getListPrice()).get(seletUnit).getWid());
db.insetCArt(mcart);
/*int isQty = db.isProduct(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getPid());
if (isQty != -1 && isQty != 0) {
int tQ = mQty + isQty;
mcart.setQty(tQ);
db.updateCart(mcart);
} else {
db.insetCArt(mcart);
}*/
/*CartFragment orderFrg = new CartFragment();
Bundle args = new Bundle();
orderFrg.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.frmae, orderFrg).addToBackStack(null).commit();
*/
}

My Count Down Timer is not properly working for Listview in android

When am set Count down timer for single progress circle its work perfectly but when am using it for Listview my Progress Circle not work perfectly. Please tell me How to implement count down timer for listview in android.
private ListView lvHomeItems;
private List<HomeContent> homeListContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
lvHomeItems = (ListView) findViewById(R.id.lv_home_activity);
homeListContent = new ArrayList<>();
homeListContent.add(new HomeContent("3","22-10-2016","BDOI501",System.currentTimeMillis() + 10000));
homeListContent.add(new HomeContent("2","21-10-2016","BDOI502",System.currentTimeMillis() + 22000));
homeListContent.add(new HomeContent("4","20-10-2016","BDOI503",System.currentTimeMillis() + 34000));
homeListContent.add(new HomeContent("1","19-10-2016","BDOI504",System.currentTimeMillis() + 46000));
lvHomeItems.setAdapter(new CountdownAdapter(HomeActivity.this, homeListContent));
}
private class HomeContent {
long expirationTime;
String Date;
String Id;
String PrescriptionNo;
public HomeContent(String PrescriptionNo,String Date,String Id,long expirationTime) {
this.expirationTime = expirationTime;
this.PrescriptionNo = PrescriptionNo;
this.Date = Date;
this.Id = Id;
}
}
public class CountdownAdapter extends ArrayAdapter<HomeContent> {
private LayoutInflater layoutInflater;
private List<ViewHolder> homeListContent;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (homeListContent) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : homeListContent) {
holder.updateTimeRemaining(currentTime);
}
}
}
};
public CountdownAdapter(Context context, List<HomeContent> objects) {
super(context, 0, objects);
layoutInflater = LayoutInflater.from(context);
homeListContent = new ArrayList<>();
startUpdateTimer();
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.home_list_content, parent, false);
holder.tvCountDownTimer = (TextView) convertView.findViewById(R.id.tv_home_countTimeDown);
holder.tvDate = (TextView) convertView.findViewById(R.id.tv_home_date);
holder.tvOrderId = (TextView) convertView.findViewById(R.id.tv_home_order_id);
holder.tvPrescriptionNo = (TextView) convertView.findViewById(R.id.tv_priscription_no);
holder.tvViewDetails = (TextView) convertView.findViewById(R.id.tv_view);
holder.btnSelectBid = (Button) convertView.findViewById(R.id.btn_select_bid);
holder.mRingProgressBar = (RingProgressBar) convertView.findViewById(R.id.progress_bar_1);
//doSomeThing();
holder.tvViewDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this,PrescriptionListActivity.class);
startActivity(intent);
}
});
holder.btnSelectBid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// bidVenderList();
Intent intent = new Intent(HomeActivity.this,SelectBidActivity.class);
startActivity(intent);
}
});
convertView.setTag(holder);
synchronized (homeListContent) {
homeListContent.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData(getItem(position));
return convertView;
}
}
private class ViewHolder {
TextView tvViewDetails, tvCountDownTimer, tvDate, tvOrderId, tvPrescriptionNo;
Button btnSelectBid;
HomeContent mProduct;
RingProgressBar mRingProgressBar;
public void setData(HomeContent item) {
mProduct = item;
tvOrderId.setText("Order Id : " + item.Id);
tvDate.setText("Date : " + item.Date);
tvPrescriptionNo.setText("No of Prescription : " + item.PrescriptionNo);
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
final long timeDiff = mProduct.expirationTime - currentTime;
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus += 1;
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mRingProgressBar.setProgress(mProgressStatus);
mRingProgressBar.setMax(60);
if (timeDiff > 0) {
final int seconds = (int) (timeDiff / 1000) % 60;
final int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
tvCountDownTimer.setText(minutes + " : " + seconds);
}
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
When am start my activity it not work perfectly... please tell me solution

I create a RecyclerView in Fragment but while reloading data RecyclerView does not maintains state.

//I have created RecycleView in Fragment as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_shop, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
stackView = (RelativeLayout) view.findViewById(R.id.stack_view);
firstStack = (CustomImageView) view.findViewById(R.id.firstStack);
secondStack = (CustomImageView) view.findViewById(R.id.secondStack);
thirdStack = (CustomImageView) view.findViewById(R.id.thirdStack);
stackTopGap = view.findViewById(R.id.view);
new Handler().post(new Runnable() {
#Override
public void run() {
firstStack.getLayoutParams().width = stackView.getWidth() - 40;
secondStack.getLayoutParams().width = stackView.getWidth() - 80;
thirdStack.getLayoutParams().width = stackView.getWidth() - 120;
width = thirdStack.getLayoutParams().width;
recyclerView.getLayoutParams().height = recyclerView.getHeight() - (firstStack.getHeight() + stackTopGap.getHeight());
stackView.getLayoutParams().height = firstStack.getHeight();
}
});
recyclerView.setHasFixedSize(true);
linearLayoutManager=new LinearLayoutManager(getActivity()) {
#Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
// A good idea would be to create this instance in some initialization method, and just set the target position in this method.
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(getContext()) {
#Override
public PointF computeScrollVectorForPosition(int targetPosition) {
//int yDelta = calculateCurrentDistanceToPosition(targetPosition);
return new PointF(0, 200);
}
// This is the important method. This code will return the amount of time it takes to scroll 1 pixel.
// This code will request X milliseconds for every Y DP units.
#Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 7 / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 7, displayMetrics);
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(final RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
final int positionView = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (dy > 0) {
if (positionView >= 2) {
final View view = recyclerView.getChildAt(2);
if (view != null && recyclerView.getChildAdapterPosition(view) == positionView) {
TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 200, 0);
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
if (counter == 0) {
if (recyclerView.getAdapter().getItemCount() - 4 >= positionView) {
createStackImageView();
}
if (stackView.getChildAt(1) != null) {
//stackView.getChildAt(1).setScaleX(1.5f);
}
counter++;
}
recyclerView.smoothScrollToPosition(positionView);
}
#Override
public void onAnimationEnd(Animation animation) {
view.clearAnimation();
stackView.requestLayout();
stackView.removeView(stackView.getChildAt(1));
stackView.invalidate();
try {
for (int i = 1; i < 4; i++) {
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(positionView + i))
.into((ImageView) stackView.getChildAt(i));
}
} catch (IndexOutOfBoundsException | NullPointerException | IllegalArgumentException ex) {
ex.printStackTrace();
}
counter = 0;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
translateAnimation.setDuration(150);
view.setAnimation(translateAnimation);
}
}
for (int i = stackView.getChildCount() - 1; i >= 2; i--) {
ResizeAnimation resizeAnimation = new ResizeAnimation(stackView.getChildAt(i));
resizeAnimation.setHeights(stackView.getChildAt(i).getHeight(), stackView.getChildAt(i - 1).getHeight());
resizeAnimation.setWidths(stackView.getChildAt(i).getWidth(), stackView.getChildAt(i - 1).getWidth());
resizeAnimation.setDuration(200);
stackView.getChildAt(i).startAnimation(resizeAnimation);
}
} else if (dy < 0) {
final int position = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (position == imageList.size() - 1) {
stackView.removeView(firstStack);
stackView.addView(firstStack);
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(1).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 1))
.into((ImageView) stackView.getChildAt(1));
} else if (position == imageList.size() - 2) {
stackView.removeView(secondStack);
stackView.addView(secondStack);
secondStack.getLayoutParams().height = firstStack.getHeight() - 20;
secondStack.getLayoutParams().width = firstStack.getWidth() - 40;
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(2).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 2))
.into((ImageView) stackView.getChildAt(2));
} else if (position == imageList.size() - 3) {
stackView.removeView(thirdStack);
stackView.addView(thirdStack);
thirdStack.getLayoutParams().height = secondStack.getHeight() - 20;
thirdStack.getLayoutParams().width = secondStack.getWidth() - 40;
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(3).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 3))
.into((ImageView) stackView.getChildAt(3));
} else {
stackView.removeView(firstStack);
stackView.addView(firstStack);
stackView.invalidate();
stackView.requestLayout();
}
}
}
});
return view;
}
//In validateToken method data is taken from the json and set to adapter as follows.
private void validateToken() {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (new ConnectionManager(getActivity()).isConnectedToInternet()) {
final SweetAlertDialog pDialog = new AlertDIalogMessage().showProgressDialog(getActivity(), "Loading...");
if (sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, "token_invalid").equals("token_invalid")) {
Utils.setTokenInfo(getActivity(), pDialog, new AccessTokenInfoHolder() {
#Override
public void setAcessTokenInfo(String accessToken, String expires_in, String token_type) {
Log.e("Access Token", accessToken);
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//do nothing here since the case unauthorized will not arrive for the first time
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
shoppageInfoList = getShopPageContent(data);
//set the adapter after loading data from url
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
});
} else {
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//this method is invoked when unauthorized response come from server
Utils.setTokenInfo(getActivity(), pDialog, new AccessTokenInfoHolder() {
#Override
public void setAcessTokenInfo(String accessToken, String expires_in, String token_type) {
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//do nothing here since the case unauthorized will not arrive for the first time
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
List<ShoppageInfo> shoppageInfoList = getShopPageContent(data);
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
});
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
List<ShoppageInfo> shoppageInfoList = getShopPageContent(data);
//set the adapter after loading data from url
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
} else {
new SweetAlertDialog(getActivity(), SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No internet connection!")
.show();
}
}
No in onResume method i called validate token as follows:
#Override
public void onResume() {
super.onResume();
validateToken();
}
//Now when I call some activity from this fragment and come back with back pressed validate method is called and RecyclerView adapter is reloaded. Now what I want is to maintain the state of RecyclerView such that when I came back from activity RecyclerView stays in the scroll position from when activity is called. But problem for me is it always come from the start. I also see some Stack Overflow post and they suggest me to use Parceable but i don't get any benefit. Is is doing nothing.
Can try this.
You need to maintain an identifier for each row. Then save the first visible row's identifier before you go to the activity. Then when you come back you select that particular row again.

Categories

Resources