How Can I catch Google Play Subscriptions Payment - java

I try to google play subscription billing. Code is working doing payment. But I want to try when a payment successfull ı want to catch payment cost,time(montly,yearly) and I send my php API for example with an ID or Token. How can i do this.
I tried overriding onPurchasesUpdated
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
}
but it didn't work . I tried show a toast. But method didn't work.
Can I do this with this method If I can how can I run this method ?
public void openPayment(final Context mContext){
final List<String> skuList = new ArrayList<>();
//valueof1MonthMoney,valueof3MonthsMoney,valueof6MonthsMoney,valueof1YearMoney;
skuList.add("com.yeniasya.enewspaper.subscription.onemonth");
skuList.add("com.yeniasya.enewspaper.subscription.threemonth");
skuList.add("com.yeniasya.enewspaper.subscription.sixmonth");
skuList.add("com.yeniasya.enewspaper.subscription.oneyear");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext,android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View mView = li.inflate(R.layout.popup_payment, null);
ImageView imvClose=(ImageView)mView.findViewById(R.id.imvClose);
final TextView tv1MonthMoney = (TextView) mView.findViewById(R.id.tv1MonthMoney);
final TextView tv3MonthsMoney = (TextView) mView.findViewById(R.id.tv3MonthsMoney);
final TextView tv6MonthsMoney = (TextView) mView.findViewById(R.id.tv6MonthsMoney);
final TextView tv1YearMoney = (TextView) mView.findViewById(R.id.tv1YearMoney);
final TextView tvOpenPrivacy = (TextView) mView.findViewById(R.id.tvOpenPrivacy);
final LinearLayout linLay1Year = (LinearLayout) mView.findViewById(R.id.linLay1Year);
final LinearLayout linLay6Months = (LinearLayout) mView.findViewById(R.id.linLay6Months);
final LinearLayout linLay3Months = (LinearLayout) mView.findViewById(R.id.linLay3Months);
final LinearLayout linLay1Month = (LinearLayout) mView.findViewById(R.id.linLay1Month);
mBuilder.setView(mView);
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
final SkuDetails[] s = new SkuDetails[4];
params.setSkusList(skuList).setType(BillingClient.SkuType.SUBS);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
s[0] =skuDetailsList.get(0);
s[1] =skuDetailsList.get(1);
s[2] =skuDetailsList.get(2);
s[3] =skuDetailsList.get(3);
// Toast.makeText(mContext, "listeye girdi", Toast.LENGTH_SHORT).show();
try {
tv1MonthMoney.setText(skuDetailsList.get(0).getPrice());
tv1YearMoney.setText(skuDetailsList.get(1).getPrice());
tv6MonthsMoney.setText(skuDetailsList.get(2).getPrice());
tv3MonthsMoney.setText(skuDetailsList.get(3).getPrice());
/* if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.onemonth"));
tv1MonthMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.threemonth"));
tv3MonthsMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.sixmonth"));
tv6MonthsMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.oneyear"));
tv1YearMoney.setText(skuDetailsList.get(i).getPrice()+""); */
// Toast.makeText(mContext, skuDetailsList.get(i).getSku()+"", Toast.LENGTH_SHORT).show();
}catch (Exception e){
}
}
});
dialog.show();
imvClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
linLay1Year.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[1]);
}
});
linLay1Month.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[0]);
}
});
linLay3Months.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[3]);
}
});
linLay6Months.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[2]);
}
});
tvOpenPrivacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Intent i = new Intent(Intent.ACTION_VIEW);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse(mcontext.getString(R.string.PrivacyPolicyUrl)));
mcontext.startActivity(i);}catch (Exception e){}
}
});
}
private void takeMoney(SkuDetails skuDetails){
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build();
billingClient.launchBillingFlow(MainActivity.mActivity,flowParams);
// Toast.makeText(mContext, "bastın3", Toast.LENGTH_SHORT).show();
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
}

Related

Dialog dismiss not working inside adapter

I have a modal(dialog) with a edit text inside and a send button, what i'm trying to do is simply send the content inside the edit text when the button is clicked, the thing is, sending the content is working, but when i call mydialog.dismiss(); it doesn't work. It is using an instance of another class to call a method retrofit, and inside the "done" and "not done" buttons i have the "enviar"(send) button which is the one i'm trying to close the modal with.
Here is the adapter code:
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent){
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(sContext).inflate(R.layout.item_tasks, parent,false);
final Tasks presenteTask = taskData.get(position);
TextView taskTitle = (TextView) listItem.findViewById(R.id.tasksTitle);
taskTitle.setText(presenteTask.getTitle());
EditText taskColor = (EditText) listItem.findViewById(R.id.taskColor);
if(presenteTask.getHexaColor().isEmpty()){
HexaColor = "#FFFFFF";
}
else{
HexaColor = presenteTask.getHexaColor();
taskColor.setBackgroundColor(Color.parseColor(HexaColor));
}
TextView taskTime = (TextView) listItem.findViewById(R.id.taskTime);
taskTime.setText(presenteTask.getTimeStart().toString().substring(0,5));
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false);
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final EditText comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
final Calendario calendario = new Calendario();
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
return listItem;
}
}
Thank you very much!
Firstly you have to make your dialog un-cancelable, so that outside click doesn't dismiss it using tasksModal.setCancelable(false);
Secondly no need to repeat code to create dialog inside done/undone button click. So, remove it and move it to TasksAdapter constructor.
Thirdly You are not dismissing your dialog inside done button click. So, add this tasksModal.dismiss();
Check and try with below code:
EditText comentarios;
Calendario calendario;
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false); //make it un cancelable
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
calendario = new Calendario();
}
-------------------------------------------------------------
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(!comentario.equals("")){
tasksModal.dismiss(); //dismiss here
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
else{
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
else{
tasksModal.dismiss();
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
}
});
tasksModal.show();
}
});

Firebase removeValue()

I have a problem to write a code to delete database.
I would like to delete this:
I don't know how to use .child() in this situation. My code for now is:
private void deleteKryterium(String kryteriumId) {
DatabaseReference drKryteria = FirebaseDatabase.getInstance().getReference().child(kryteriumId);
drKryteria.child(kryteriumId).removeValue();
Toast.makeText(this,"Kryterium zostało usunięte", Toast.LENGTH_LONG).show();
}
But it is wrong. Can you help me? Most of the code I wrote from tutorials, so it's very green.
On the other side code which is designated to update this child, is working fine:
private boolean updateKryterium(String id, String name, int rating){
Kryterium kryterium = new Kryterium(id, name, rating);
databaseKryteria.child(id).setValue(kryterium);
Toast.makeText(this, "Nazwa kryterium zaktualizowana", Toast.LENGTH_LONG).show();
return true;
You are not pointing to the correct reference you want to remove.
The path to that child should start from:
DatabaseReference drKryteria = FirebaseDatabase.getInstance().getReference().child("piwo_kryteria");
Then at that point, you should move to the child with key -LI785bPiLU9Z2qEe35o and then finally to the child you want to remove (with id kryteriumId).
You should know the value of the intermediate key as you do for the kyteriumId.
Notice that you can also use 1 single child() function passing to it the entire path in which each node is separated by forward-slashes like:
.child("piwo_kryteria/" + intermediate_key + "/" + kryteriumId)
On that reference you will call removeValue() or even setValue(null).
this is a code for now, ofcourse it is not working correctly in deleting items:
public class Piwo_AddKryterium extends AppCompatActivity {
TextView textViewAlkoholName, textViewRating;
SeekBar seekBarRating;
Spinner spinnerKryteria;
Button buttonAddKryterium;
ListView listViewKryteria;
DatabaseReference databaseKryteria;
List<Kryterium> kryteria;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.piwo_activity_add_kryterium);
textViewAlkoholName = (TextView) findViewById(R.id.textViewAlkoholName);
seekBarRating = (SeekBar) findViewById(R.id.seekBarRating);
textViewRating = (TextView) findViewById(R.id.textViewRating);
buttonAddKryterium = (Button) findViewById(R.id.buttonAddKryterium);
listViewKryteria = (ListView) findViewById(R.id.listViewKryteria);
spinnerKryteria = (Spinner) findViewById(R.id.spinnerKryteria);
Intent intent = getIntent();
kryteria = new ArrayList<>();
String id = intent.getStringExtra(Piwo_Program.ALKOHOL_ID);
String name = intent.getStringExtra(Piwo_Program.ALKOHOL_NAME);
textViewAlkoholName.setText(name);
databaseKryteria = FirebaseDatabase.getInstance().getReference("piwo_kryteria").child(id);
buttonAddKryterium.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveKryterium();
}
});
seekBarRating.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textViewRating.setText(String.valueOf(i));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
listViewKryteria.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
listViewKryteria.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Kryterium kryterium = kryteria.get(i);
showUpdateDialog(kryterium.getKryteriumId(), kryterium.getKryteriumName());
return true;
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseKryteria.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
kryteria.clear();
for(DataSnapshot kryteriumSnapshot : dataSnapshot.getChildren()){
Kryterium kryterium = kryteriumSnapshot.getValue(Kryterium.class);
kryteria.add(kryterium);
}
KryteriumList kryteriumListAdapter = new KryteriumList(Piwo_AddKryterium.this, kryteria);
listViewKryteria.setAdapter(kryteriumListAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void saveKryterium(){
String kryteriumName = spinnerKryteria.getSelectedItem().toString();
int rating = seekBarRating.getProgress();
if(!TextUtils.isEmpty(kryteriumName)){
String id = databaseKryteria.push().getKey();
Kryterium kryterium = new Kryterium(id, kryteriumName, rating);
databaseKryteria.child(id).setValue(kryterium);
Toast.makeText(this, "Kryterium zapisane poprawnie", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Nazwa kryterium nie może pozostać pusta", Toast.LENGTH_SHORT).show();
}
}
private void showUpdateDialog(final String kryteriumId, String kryteriumName){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.piwo_update_dialog_kryterium, null);
dialogBuilder.setView(dialogView);
final Spinner spinnerKryteria = (Spinner) dialogView.findViewById(R.id.spinnerKryteria);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdate);
final SeekBar seekBarRating = (SeekBar) dialogView.findViewById(R.id.seekBarRating);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Aktualizacja Kryterium: " + kryteriumName);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String kryteriumName = spinnerKryteria.getSelectedItem().toString();
int rating = seekBarRating.getProgress();
updateKryterium(kryteriumId, kryteriumName, rating);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteKryterium(kryteriumId);
alertDialog.dismiss();
}
});
}
private void deleteKryterium(String kryteriumId) {
DatabaseReference drKryteria = FirebaseDatabase.getInstance().getReference().child(kryteriumId);
drKryteria.child(kryteriumId).removeValue();
Toast.makeText(this,"Kryterium zostało usunięte", Toast.LENGTH_LONG).show();
}
private boolean updateKryterium(String id, String name, int rating){
Kryterium kryterium = new Kryterium(id, name, rating);
databaseKryteria.child(id).setValue(kryterium);
Toast.makeText(this, "Nazwa kryterium zaktualizowana", Toast.LENGTH_LONG).show();
return true;
}
}

Setting the dataset for Recyclerview after filter

I am filtering my data using onQueryTextChange, the list filters but it still shows the old data set(unfiltered) which results in data from the old list, even though it shows the new filtered list.
Can someone fix my code which will display the right data set after filter, and unfiltered dataset when the a user will clear the search text.
I will explain it better with screenshots.
Before filter Screenshot 1, clicking on a item will toast the text on it.
After Filter Screenshot 2, on click it is supposed to say HDFC BANK, instead it still shows the data from Position 1 from the unfiltered data set.
I was told its because I am using the BankNames List (unfiltered) text at position when clicking, because of which this is happening.
Can someone please fix my logic here, I am unable to figure this out, even though it seems simple, I am new to Android.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{
List<DataAdapter> DataAdapterClassList;
RecyclerView recyclerView;
final List<DataAdapter> filteredModelList = new ArrayList<>();
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerViewAdapter recyclerViewadapter;
ProgressBar progressBar;
JsonArrayRequest jsonArrayRequest;
ArrayList<String> BankNames;
RequestQueue requestQueue;
String HTTP_SERVER_URL = "http://hiddenforsecurity.com";
View ChildView;
int RecyclerViewClickedItemPOS;
LinearLayout lyt, icicBtn, hdfcBtn, axisBtn, sbiBtn, pnbBtn, yesBtn;
private static int firstVisibleInListview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataAdapterClassList = new ArrayList<>();
BankNames = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
lyt = (LinearLayout) findViewById(R.id.Layout1);
final Intent go = new Intent(MainActivity.this, StateList.class);
icicBtn = (LinearLayout) findViewById(R.id.icicBtn);
hdfcBtn = (LinearLayout) findViewById(R.id.hdfcBtn);
axisBtn = (LinearLayout) findViewById(R.id.axisBtn);
sbiBtn = (LinearLayout) findViewById(R.id.sbiBtn);
pnbBtn = (LinearLayout) findViewById(R.id.pnbBtn);
yesBtn = (LinearLayout) findViewById(R.id.yesBtn);
final Intent i = new Intent(this, StateList.class);
// JSON data web call function call from here.
JSON_WEB_CALL();
//RecyclerView Item click listener code starts from here.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
//Printing RecyclerView Clicked item clicked value using Toast Message.
//i.putExtra("selectedbank", BankNames.get(RecyclerViewClickedItemPOS));
//startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
icicBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "ICICI BANK LIMITED");
startActivity(go);
}
});
axisBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "AXIS BANK");
startActivity(go);
}
});
hdfcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "HDFC BANK");
startActivity(go);
}
});
sbiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "STATE BANK OF INDIA");
startActivity(go);
}
});
pnbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "PUNJAB NATIONAL BANK");
startActivity(go);
}
});
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "YES BANK");
startActivity(go);
}
});
}
public void JSON_WEB_CALL(){
progressBar.setVisibility(View.VISIBLE);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setBankName(json.getString("BANK"));
//Adding subject name here to show on click event.
BankNames.add(json.getString("BANK"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataAdapter2);
}
progressBar.setVisibility(View.GONE);
recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
private List<DataAdapter> filter(List<DataAdapter> models, String query) {
query = query.toLowerCase();
final List<DataAdapter> filteredModelList = new ArrayList<>();
for (DataAdapter model : models) {
final String text = model.getBankName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
recyclerViewadapter = new RecyclerViewAdapter(filteredModelList, MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerViewadapter);
recyclerViewadapter.notifyDataSetChanged();
return filteredModelList;
}
}
RecyclerviewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
public DataAdapter dataAdapter;
List<DataAdapter> dataAdapters;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
dataAdapter = dataAdapters.get(position);
viewHolder.TextViewName.setText(dataAdapter.getBankName());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView TextViewName;
public ViewHolder(View itemView) {
super(itemView);
TextViewName = (TextView) itemView.findViewById(R.id.TextViewCard) ;
}
}
public void setFilter(List<DataAdapter> bankNames) {
dataAdapters = new ArrayList<>();
dataAdapters.addAll(bankNames);
notifyDataSetChanged();
}
}
Make global variable for filteredList and take data from that list. The error happened because you are toasting from the full list. Not filteredList
Try this
may this issue that your are Printing Toast of BankNames.get(RecyclerViewClickedItemPOS) from your Oldlist not From the filteredModelList
Remove this
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
and set Toast in Adapter class
viewHolder.TextViewName..setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, dataAdapter.getBankName(), Toast.LENGTH_SHORT).show();
}
});

cannot be reference from a static context, run in other class

I would like to put the function run_voice() of my MainActivity on my class TypingDialogFragment but it do not work:
Non static method 'run_voice' cannot be reference from a static context
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
Home1=(ImageView)findViewById(R.id.home);
Voice1=(ImageView)findViewById(R.id.voice);
Scan1=(ImageView)findViewById(R.id.scan);
frequence_text=(TextView)findViewById(R.id.frequence_text);
command_text=(TextView)findViewById(R.id.command_text);
gain_text=(TextView) findViewById(R.id.gain_text);
body = (TextView)findViewById(R.id.body);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab_frequence = (FloatingActionButton) findViewById(R.id.freq_value);
fab_gain = (FloatingActionButton) findViewById(R.id.gain_value);
send_voice = (ImageButton) findViewById(R.id.send_voice1);
send_voice2 = (ImageView) findViewById(R.id.send_voice3);
myChrono=(Chronometer) findViewById(R.id.chronometer);
progressBar=(ProgressBar) findViewById(R.id.progressBar);
body.setMovementMethod(new ScrollingMovementMethod());
setSupportActionBar(toolbar);
OUTPUT_FILE= Environment.getExternalStorageDirectory()+ "/audiorecord.wav";
outFile=new File (OUTPUT_FILE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
type = 1;
showCmdLineDialog(type,run_voice);
}
});
fab_frequence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
type = 2;
showCmdLineDialog(type,run_voice);
}
});
fab_gain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
type = 3;
showCmdLineDialog(type,run_voice);
}
});
display_mediaplayer_false();
display_floatbutton_false();
success1=0;
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)){
Toast.makeText(this, "FEATURE_BLUETOOTH NOT support", Toast.LENGTH_LONG).show();
finish();
return;
}
//using the well-known SPP UUID
myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this hardware platform", Toast.LENGTH_LONG).show();
finish();
return;
}
Home1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(success1==1)
{
display_mediaplayer_false();
display_floatbutton_true();
}
}
});
Voice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(success1==1) {
display_floatbutton_false();
display_mediaplayer_true();
}
}
});
Scan1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(success1==1) {
display_floatbutton_false();
display_mediaplayer_false();
}
}
});
send_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
run_voice(); // FUNCTION RUN VOICE
}
});
}
My function run_voice :
public void run_voice()
{
try {
if (color==0)
{
send_voice.setColorFilter(Color.RED);
beginRecording();
progressBar.setVisibility(View.VISIBLE);
myChrono.setBase(SystemClock.elapsedRealtime());
myChrono.start();
color1=1;
run_voice=1;
}
if (color==1)
{
send_voice.setColorFilter(Color.BLACK);
progressBar.setVisibility(View.INVISIBLE);
stopRecording();
myChrono.stop();
color1=0;
run_voice=0;
}
color=color1;
}
catch (IOException e) {
e.printStackTrace();
}
}
I would like to put this function in this class :
public static class TypingDialogFragment extends DialogFragment {
EditText cmdLine;
static MainActivity parentActivity;
static ThreadConnected cmdThreadConnected;
static int type1;
static int run_voice1;
static TypingDialogFragment newInstance(MainActivity parent, ThreadConnected thread, int type, int run_voice){
type1=type;
run_voice1=run_voice;
parentActivity = parent;
cmdThreadConnected = thread;
TypingDialogFragment f = new TypingDialogFragment();
return f;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().setTitle("Cmd Line");
getDialog().setCanceledOnTouchOutside(false);
View typingDialogView = inflater.inflate(R.layout.typing_layout, container, false);
cmdLine = (EditText)typingDialogView.findViewById(R.id.cmdline);
ImageView imgCleaarCmd = (ImageView)typingDialogView.findViewById(R.id.clearcmd);
imgCleaarCmd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cmdLine.setText("");
}
});
ImageButton send_voice=(ImageButton)getActivity().findViewById(R.id.send_voice1);
send_voice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
byte[] NewLine = "\n".getBytes();
byte[] bytesToSend="pkill -f receiverfm.py".getBytes();
byte[] bytesToSend2="./emetteur.py".getBytes();
byte[] bytesToSend3="pkill -f emetteur.py".getBytes();
byte[] bytesToSend4="./receiverfm.py".getBytes();
if (run_voice1==0)
{
cmdThreadConnected.write(bytesToSend);
cmdThreadConnected.write(NewLine);
cmdThreadConnected.write(bytesToSend2);
}
if (run_voice1==1)
{
cmdThreadConnected.write(bytesToSend3);
cmdThreadConnected.write(NewLine);
cmdThreadConnected.write(bytesToSend4);
}
cmdThreadConnected.write(NewLine);
}
});
Button btnEnter = (Button)typingDialogView.findViewById(R.id.enter);
btnEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cmdThreadConnected!=null){
byte[] memory_freq="100.0".getBytes();
if (type1==1)
{
byte[] bytesToSend = cmdLine.getText().toString().getBytes();
cmdThreadConnected.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
cmdThreadConnected.write(NewLine);
}
if (type1==2)
{
byte[] byteToSend_freq = "./receiverfm.py --freq ".getBytes();
byte[] bytesToSend = cmdLine.getText().toString().getBytes();
memory_freq=bytesToSend;
cmdThreadConnected.write(byteToSend_freq);
cmdThreadConnected.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
cmdThreadConnected.write(NewLine);
}
if (type1==3)
{
byte[] byteToSend_gain="./receiverfm.py --freq ".getBytes();
cmdThreadConnected.write(byteToSend_gain);
cmdThreadConnected.write(memory_freq);
byte[] byteToSend_gain2=" --".getBytes();
byte[] bytesToSend = cmdLine.getText().toString().getBytes();
cmdThreadConnected.write(byteToSend_gain2);
cmdThreadConnected.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
cmdThreadConnected.write(NewLine);
}
}
}
});
Button btnDismiss = (Button)typingDialogView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
Button btnClear = (Button)typingDialogView.findViewById(R.id.clear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
body.setText("");
}
});
return typingDialogView;
}
}

Im about to refresh the current viewed Fragment from searching an item from API

In my application I am about to refresh the current viewed fragment after searching an item from API. My search bar is coming from Fragment activity and, when the result is there, it will be viewed in the second fragment, but the problem is, when I click search, it will reset into the 1st fragment.
Here's my code:
private ViewPager mPager;
private MyPagerAdapter mAdapter;
ImageView settings_btn;
EditText search;
//EditText search;
ImageView community_icon;
ImageView loyalty_icon;
ImageView tokens_icon;
Context context;
public CustomerAccount customerAccount;
private MyPagerAdapter pagerAdapter;
String offer = "cheese";
ProgressDialog progressDialog;
CustomListAdapterMerchant adapter;
String searchname;
ArrayList<RowItemMerchant> rowItem;
JSONObject offerlist;
int i;
JSONObject merchantList;
RowItemMerchant items;
ListView listView;
Bundle extras;
String empty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
if(savedInstanceState != null){
search.setText(savedInstanceState.getString("Key"));
}
search = (EditText) findViewById(R.id.searchView);
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
ConstantSearch.SEARCHNAME = search.getText().toString();
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.d("SearchName",ConstantSearch.SEARCHNAME);
return true;
}
return false;
}
});
search.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// You can identify which key pressed buy checking keyCode value
// with KeyEvent.KEYCODE_
if (keyCode == KeyEvent.KEYCODE_DEL) {
ConstantSearch.SEARCHNAME = "";
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.e("IME_TEST", "DEL KEY");
}
return false;
}
});
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null) {
String getName = (String) bd.get("IPUTTEDMERCHANT");
search.setText(getName);
}
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!enabled) {
showDialogGPS();
}
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setAdapter(mAdapter);
final TextView ref1= (TextView) findViewById(R.id.ref1);
final TextView ref2= (TextView) findViewById(R.id.ref2);
final TextView ref3= (TextView) findViewById(R.id.ref);
final ImageView Image1 = (ImageView) findViewById(R.id.image1);
final ImageView Image2 = (ImageView) findViewById(R.id.image2);
final ImageView Image3 = (ImageView) findViewById(R.id.image3);
settings_btn = (ImageView) findViewById(R.id.settings_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent settings = new Intent(DashboardActivity.this, SettingsPromotion.class);
startActivity(settings);
}
});
ref1.setTextColor(ContextCompat.getColor(this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
ref1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
setToDefault();
ref1.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
}
});
loyalty.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(1);
setToDefault();
ref2.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image2.setImageResource(R.drawable.ic_loyalty_on);
}
});
tokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(2);
setToDefault();
ref3.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image3.setImageResource(R.drawable.ic_tokens_on);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);{
String savedText = search.getText().toString();
savedInstanceState.putString("Key", savedText);
}
}
private void showDialogGPS() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Allow \"My App\" to access you location while you use tha app?");
builder.setMessage("My App uses this to help customers find places. connect with merchants and more");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(
new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void setToDefault()
{
TextView ref1 = (TextView) findViewById(R.id.ref1);
TextView ref2 = (TextView) findViewById(R.id.ref2);
TextView ref3 = (TextView) findViewById(R.id.ref3);
ImageView Image1 = (ImageView) findViewById(R.id.image1);
ImageView Image2 = (ImageView) findViewById(R.id.image2);
ImageView Image3 = (ImageView) findViewById(R.id.image3);
ref1.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image1.setImageResource(R.drawable.ic_community_off);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
private static final int NUM_ITEMS = 3;
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
private FragmentThree fragmentThree;
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
mFragmentTags = new HashMap<Integer, String>();
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
fragmentThree = new FragmentThree();
}
#Override
public int getCount()
{
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position)
{
if (position == 0)
{
return fragmentOne;
}
else if (position == 1)
{
return fragmentTwo;
}
else if (position == 2)
{
return fragmentThree;
}
else
{
Log.e("AuthActivity", "ViewPager invalid position");
return null;
}
}
}

Categories