When using setOnGroupClickListener method report an error “cannot find symbol”,
I try to use setOnGroupClickListener to register sublist click event listener to list control,But an error is reported during compilation
error report:
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:142: error: cannot find symbol
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:143: error: method does not override or implement a method from a supertype
#Override
package com.mtb.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import com.xiaomi.mtb.*;
import com.xiaomi.mtb.activity.*;
import com.xiaomi.mtb.R;
import android.util.Log;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MtbNvAutoCheckList1Activity extends MtbBaseActivity {
private ArrayList<NvAutoCheckDataFather> groups = new ArrayList<>();
private ArrayList<ArrayList<NvAutoCheckDataSon>>children = new ArrayList<>();
private ArrayList<NvAutoCheckDataSon>data=new ArrayList<>();
private HashMap<Integer,Integer>hashMap=new HashMap<>();
private static int mNvEfsDataPrintMaxNum = 20;
private static final String LOG_TAG = "MtbNvAutoCheckMainActivity";
private static final int DATA_TYPE_DECIMALISM = 0;
private static int mHexOrDec = DATA_TYPE_DECIMALISM;
private static final int DATA_TYPE_HEX = 1;
private static final int SIGNED_DATA = 0;
private static final int UNSIGNED_DATA = 1;
private static boolean mTmpLogPrintFlag = false;
private ExpandableListView elvBook;
private NvAutoCheckBookAdapter adapter;
private static HashMap<Integer,byte[]>mNvData=new HashMap<Integer,byte[]>(){
{
put(550,new byte[]{8,(byte)138, 70, 115, 6, 98, 16, 5, 112});
put(74,new byte[]{6});
put(453,new byte[]{1});
}
};
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMtbHookAgent = MtbHookAgent.getHook();
int num=0;
Iterator<Map.Entry<Integer,byte[]>> iterator1=mNvData.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry<Integer,byte[]>entry=iterator1.next();
int key=entry.getKey();
byte[] value=entry.getValue();
ByteBuffer byteBuf=mMtbHookAgent.onHookNvOptSync(0, key, mMtbHookAgent.EVENT_OEMHOOK_XIAOMI_NV_READ);
log("onNvEfsReadHookHdl, mNvId = "+key);
int ret = byteBuf.getInt();
int len = byteBuf.getInt();
log("onNvEfsReadHookHdl" + ", len = " + len);
byte[] bytes = null;
if(len<=0){
log("efs config empty");
}else{
bytes = new byte[len];
byteBuf.get(bytes);
}
String mNvFlagResult="false";
for(int i=0; i < value.length;i++){
if(entry.getValue()[i] != bytes[i]){
log("mNVDATA_"+key+"[" + i + "] not the same");
break;
}
log("mNVDATA_"+key+"[" + i + "] identical");
if(i == (value.length - 1)){
mNvFlagResult = "success";
}
}
groups.add(new NvAutoCheckDataFather(key,mNvFlagResult));
if(mNvFlagResult=="false"){
hashMap.put(num, hashMap.size());
NvAutoCheckDataSon mNvAutoCheckDataSon=new NvAutoCheckDataSon("正确的值是: "+onGetStringByByteGroup(value,value.length),"读出的值为: "+onGetStringByByteGroup(bytes,value.length));
children.add(new ArrayList<NvAutoCheckDataSon>(){
{
add(mNvAutoCheckDataSon);
}
});
}
num++;
}
// 利用布局资源文件设置用户界面
setContentView(R.layout.nv_auto_check_list1_config);
// 通过资源标识获得控件实例
elvBook = findViewById(R.id.elvBook);
// 创建适配器
adapter = new NvAutoCheckBookAdapter(this, groups, children, hashMap);
// 给列表控件设置适配器
elvBook.setAdapter(adapter);
// 给列表控件注册子列表单击事件监听器
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition,long l){
if(!hashMap.containsKey(groupPosition)){
return true;
}else{
return false;
}
}
});
}
private static void log(String msg) {
Log.d(LOG_TAG, "MTB_ " + msg);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint) {
return onGetStringByDateType(val, uFlag, bPrint, mHexOrDec, true);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint, int hexOrDec, boolean fillHexZero) {
if (bPrint) {
tmpLog("onGetStringByDateType, byte, val = " + val + ", uFlag = " + uFlag + ", bPrint = " + bPrint + ", hexOrDec = " + hexOrDec + ", fillHexZero = " + fillHexZero);
}
String strVal = null;
BigDecimal bigVal;
byte lowVal = 0;
if (DATA_TYPE_HEX == hexOrDec) {
strVal = Integer.toHexString(val & 0xff);
if (1 == strVal.length() && fillHexZero) {
strVal = "0" + strVal;
}
if (bPrint) {
tmpLog("HEX, strVal = " + strVal);
}
} else {
strVal = "" + val;
if (UNSIGNED_DATA == uFlag && val < 0) {
lowVal = (byte)(val & 0x7f);
bigVal = BigDecimal.valueOf(lowVal).add(BigDecimal.valueOf(Byte.MAX_VALUE)).add(BigDecimal.valueOf(1));
strVal = bigVal.toString();
if (bPrint) {
tmpLog("val < 0, new strVal = " + strVal);
}
}
}
if (null != strVal) {
strVal = strVal.toUpperCase();
}
return strVal;
}
private String onGetStringByByteGroup(byte[] bytes, int len){
String ret="";
for(int i=0;i<len;i++){
String str1=onGetStringByDateType(bytes[i], UNSIGNED_DATA, false);
ret+=str1;
}
return ret;
}
private static void tmpLog(String msg) {
if (mTmpLogPrintFlag) {
log(msg);
}
}
}
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;
}
I'm working on an Android Security Lab. One of the tasks is : Get a list of all algorithms supported on the device. The hints are: Get the providers, get the services and then get the list of algorithms.
I have the following code that does that but I don't understand the part that gets the services and the algorithms. I'm actually discovering Java in the same time as Android ...
Can anyone help me to understand how it works please ?
import java.security.Provider;
import java.security.Security;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ListCryptoAlgo extends Activity {
static final String TAG = "ListCryptoAlgorithms";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListSupportedAlgorithms();
}
public void ListSupportedAlgorithms() {
String result = "";
// get all the providers
Provider[] providers = Security.getProviders();
for (int p = 0; p < providers.length; p++) {
// get all service types for a specific provider
Set<Object> ks = providers[p].keySet();
Set<String> servicetypes = new TreeSet<String>();
for (Iterator<Object> it = ks.iterator(); it.hasNext();) {
String k = it.next().toString();
k = k.split(" ")[0];
if (k.startsWith("Alg.Alias."))
k = k.substring(10);
servicetypes.add(k.substring(0, k.indexOf('.')));
}
// get all algorithms for a specific service type
int s = 1;
for (Iterator<String> its = servicetypes.iterator(); its.hasNext();) {
String stype = its.next();
Set<String> algorithms = new TreeSet<String>();
for (Iterator<Object> it = ks.iterator(); it.hasNext();) {
String k = it.next().toString();
k = k.split(" ")[0];
if (k.startsWith(stype + "."))
algorithms.add(k.substring(stype.length() + 1));
else if (k.startsWith("Alg.Alias." + stype +"."))
algorithms.add(k.substring(stype.length() + 11));
}
int a = 1;
for (Iterator<String> ita = algorithms.iterator(); ita.hasNext();) {
result += ("[P#" + (p + 1) + ":" + providers[p].getName() + "]" +
"[S#" + s + ":" + stype + "]" +
"[A#" + a + ":" + ita.next() + "]\n");
a++;
}
s++;
}
}
TextView tv = (TextView)findViewById(R.id.supp_alg_result);
tv.setText(result);
}
}
Security is the class that manages the security of the app. It contains array of providers that have all the security services. Within the provider they contains array of algorithm that the system use. In the first part of the provider where
if (k.startsWith("Alg.Alias."))
k = k.substring(10);
it gets the service with keyword "Alg.Alias."
I have some trouble in getting Tcp connection log of all apps. Basically, I just read the log file "/proc/Pid/net/tcp" as used here:
http://code.google.com/p/iptableslog/source/browse/src/com/googlecode/networklog/NetStat.java?r=60cb640ac27f8b4fb06f11d9d81c94591a531862
But all the destination ip address are 0.0.0.0, though some apps are connecting to Internet.
Here is my source code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textmpid = (TextView) findViewById(R.id.textView2);
Button buttonLoadTrafficStats = (Button) findViewById(R.id.button1);
buttonLoadTrafficStats.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ActivityManager mActivityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> mRunningProcess = mActivityManager.getRunningAppProcesses();
int i = 1;
int a;
String b;
int c;
for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess){
//Get name, Pid, Uid of all running process
System.out.println("Application: " +i+ " PID: " + amProcess.pid+ " (processName= " + amProcess.processName + " UID= "+amProcess.uid+")");
Log.i("Application", (i++) + "PID: " + amProcess.pid + "(processName=" + amProcess.processName + "UID="+amProcess.uid+")");
i++;
textmpid.setText("PID: "+ String.valueOf(amProcess.pid));
a = amProcess.pid;
b = String.valueOf(amProcess.pid);
ArrayList<Connection> connections = new ArrayList<Connection>();
try {
BufferedReader in = new BufferedReader(new FileReader("/proc/" + a + "/net/tcp"));
String line = b;
int z;
while((line = in.readLine()) != null) {
System.out.println(" tcp Netstat line: " + line);
line = line.trim();
String[] fields = line.split("\\s+", 10);
int fieldn = 0;
for(String field : fields) {
System.out.println(" tcp Field " + (fieldn++) + ": [" + field + "]");
int m = fieldn;
String n = field;
}
if(fields[0].equals("sl")) {
continue;
}
Connection connection = new Connection();
String src[] = fields[1].split(":", 2);
String dst[] = fields[2].split(":", 2);
System.out.println(" tcp Netstat: fields[1] " + fields[1]+" fields[2] " + fields[2]);
System.out.println(" tcp Netstat: src[0] " + src[0] +" src[1] " + src[1]);
connection.src = getAddress(src[0]);
System.out.println(" tcp Netstat: connection.src " + connection.src);
connection.spt = String.valueOf(getInt16(src[1]));
System.out.println(" tcp Netstat: connection.spt " + connection.spt);
connection.dst = getAddress(dst[0]);
System.out.println(" tcp Netstat: connection.dst " + connection.dst);
connection.dpt = String.valueOf(getInt16(dst[1]));
System.out.println(" tcp Netstat: connection.dpt " + connection.dpt);
connection.uid = fields[7];
System.out.println(" tcp Netstat: connection.uid " + connection.uid);
connections.add(connection);
}
}
catch(Exception e) {
System.out.println(" checknetlog() Exception: " + e.toString());
}
}
}
});
}
public class Connection {
String src;
String spt;
String dst;
String dpt;
String uid;
}
final String states[] = { "ESTBLSH", "SYNSENT", "SYNRECV", "FWAIT1", "FWAIT2", "TMEWAIT",
"CLOSED", "CLSWAIT", "LASTACK", "LISTEN", "CLOSING", "UNKNOWN"
};
private final String getAddress(final String hexa) {
try {
final long v = Long.parseLong(hexa, 16);
final long adr = (v >>> 24) | (v << 24) |
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
return ((adr >> 24) & 0xff) + "." + ((adr >> 16) & 0xff) + "." + ((adr >> 8) & 0xff) + "." + (adr & 0xff);
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return "-1.-1.-1.-1";
}
}
private final String getAddress6(final String hexa) {
try {
final String ip4[] = hexa.split("0000000000000000FFFF0000");
if(ip4.length == 2) {
final long v = Long.parseLong(ip4[1], 16);
final long adr = (v >>> 24) | (v << 24) |
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
return ((adr >> 24) & 0xff) + "." + ((adr >> 16) & 0xff) + "." + ((adr >> 8) & 0xff) + "." + (adr & 0xff);
} else {
return "-2.-2.-2.-2";
}
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return "-1.-1.-1.-1";
}
}
private final int getInt16(final String hexa) {
try {
return Integer.parseInt(hexa, 16);
} catch(Exception e) {
Log.w("NetworkLog", e.toString(), e);
return -1;
}
}
}
And I also added the permission "uses-permission android:name="android.permission.INTERNET".
Could someone kindly point out where I did wrong?
Oh, when I check this log "/proc/Pid/net/tcp6", I found the correct destination ip address. It seems that the connection type is tcp6 instead of tcp.
I'm facing a particular problem while parsing xml so the parser works fine until it encouters <Url/> tag which contains no value, I already made the test il my code :
static final String ImageHotel = "Url";
...
else if (name.equalsIgnoreCase("ImageHotel")){
message.setHotelImage(property.getFirstChild().getNodeValue());
if (!marchand.getImgHtlUrl().equalsIgnoreCase("")){
message.setHotelImageLink(new URL(marchand.getImgHtlUrl() + property.getFirstChild().getNodeValue()));
}else{
message.setHotelImageLink(new URL("http://localhost/noimage.jpg"));
}
}
This keep throwing error even when i tried to bypass by surrounding with try/catch..
any help is welcome
thanks.
Houssem.
I have reference to parse this file try to add your own data and get tag value....
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class NewsParsing {
NewsBeen Objnewsbeen;
Vector<NewsBeen> vectParse;
public NewsParsing() {
System.out.println("Constructor is calling Now ...");
try {
vectParse = new Vector<NewsBeen>();
// http://www.npr.org/rss/rss.php?id=1001
URL url = new URL(
"http://www.npr.org/rss/rss.php?id=1001");
URLConnection con = url.openConnection();
System.out.println("Connection is : " + con);
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
System.out.println("Reader :" + reader);
String inputLine;
String fullStr = "";
while ((inputLine = reader.readLine()) != null)
fullStr = fullStr.concat(inputLine + "\n");
InputStream istream = url.openStream();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
System.out.println("Builder : " + builder);
Document doc = builder.parse(istream);
System.out.println("Doc is : " + doc);
doc.getDocumentElement().normalize();
System.out.println("After Normlize : " + doc);
System.out.println("Root is : "
+ doc.getDocumentElement().getNodeName());
System.out
.println("-------------------------------------------------------------------------------------------------------------");
Element element = doc.getDocumentElement();
parseFile(element);
for (int index1 = 0; index1 < vectParse.size(); index1++) {
NewsBeen ObjNB = (NewsBeen) vectParse.get(index1);
System.out.println("Item No : " + index1);
System.out.println();
System.out.println("Title is : " + ObjNB.title);
System.out.println("Description is : " + ObjNB.description);
System.out.println("Pubdate is : " + ObjNB.pubdate);
System.out.println("Link is : " + ObjNB.link);
System.out.println("Guid is : " + ObjNB.guid);
System.out.println();
System.out
.println("-------------------------------------------------------------------------------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void parseFile(Node node) {
NodeList nodelist = node.getChildNodes();
for (int index = 0; index < nodelist.getLength(); index++) {
Node nodefromList = nodelist.item(index);
if (nodefromList.getNodeType() == Node.ELEMENT_NODE) {
// System.out.println("node.getNodeType() : " +
// nodefromList.getNodeType());
// System.out.println("Node is : " + node.getNodeName());
if (nodefromList.getNodeName().equalsIgnoreCase("item")) {
Objnewsbeen = new NewsBeen();
vectParse.addElement(Objnewsbeen);
}
if (nodefromList.hasChildNodes()) {
if (nodefromList.getChildNodes().item(0).getNodeName()
.equals("#text")) {
if (!nodefromList.getChildNodes().item(0)
.getNodeValue().trim().equals("")
&& Objnewsbeen != null)
if (nodefromList.getNodeName().equalsIgnoreCase(
"title")) {
Objnewsbeen.title = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("description")) {
Objnewsbeen.description = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("pubDate")) {
Objnewsbeen.pubdate = nodefromList
.getChildNodes().item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("link")) {
Objnewsbeen.link = nodefromList.getChildNodes()
.item(0).getNodeValue();
} else if (nodefromList.getNodeName()
.equalsIgnoreCase("guid")) {
Objnewsbeen.guid = nodefromList.getChildNodes()
.item(0).getNodeValue();
} else {
// System.out.println();
}
}
parseFile(nodefromList);
}
}
}
}
public static void main(String[] args) {
new NewsParsing();
}
}
The NewsBeen class is::
public class NewsBeen {
public String title;
public String description;
public String pubdate;
public String link;
public String guid;
}
I told you that surrounding with try/catch did not work, so, now it does, because i had to track the NullPointerException instead of simple Exception, like this :
try{
message.setHotelImage(property.getFirstChild().getNodeValue());
}catch(NullPointerException nEx){
marchand.setImgHtlUrl("");
}
thank you guys and sorry for this alert ;)