How to get data from a Dialog RecyclerView to its Hosted Activity? - java

Hi there I am having a trouble to get back text from the recycler View inside the dialog.
Somebody please help to get the data from dialog view to the same activity.
My data flow is:
MainActivity --> UserDetailsActivity --> dialog (RecyclerView)--->UserDetailsActivity ---> Updatebutton
what happening now is :
MainActivity --> UserDetailsActivity --> dialog (RecyclerView)--->App Crashes!!
what i want is to return the Tax include Money to the rent TextView
Below is my code to UserDetailsActivity.
UserDetailsActivity.Java
package com.ancorp.aplo.activity;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.telephony.SmsManager;
import android.widget.Toast;
import com.ancorp.aplo.R;
import com.ancorp.aplo.adapter.ChannelAdapter;
import com.ancorp.aplo.database.SqliteDatabase;
import com.ancorp.aplo.model.Contacts;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.time.Month;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class UserDetailsActivity extends AppCompatActivity {
private final static int SEND_SMS_PERMISSION_REQ=1;
public TextView textView ;
EditText name_edit;
EditText jacode_edit;
EditText phone_edit;
EditText balance_edit , paidDate_edit, paidAmount_edit, rent_edit, zone_edit;
SqliteDatabase myDB;
String header,data1,data2,timeStamp;
String month;
private Context context;
float amount;
Integer d1,d2;
Integer y;
TextView phone_text,btnRecharge, Activation, Deactivation , rent_text , zone_text,plan_text,name_text,jacode_text, Status_text, id_text;
TextView balance_text, LastPaidAmount,LastPaidDate;
int deactive = Color.RED;
int activeg = Color.GREEN;
Button btnEdit;
String id,balance, Lpdate, LpAmount,zone,rent;
String phoneNo,message;
String Status;
Button btndelete ;
ImageView editimgbtn,addimgbtn;
Spinner pkgname;
String SpinnerData;
String planAmount,chName,chId,chMoney;
private static int ACTIVE_CODE = 0;
private static int DEACTIVE_CODE = 0;
private SqliteDatabase mDatabase;
private ArrayList<Contacts> userData;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button recharges;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
mDatabase = new SqliteDatabase(this);
// getUserData(id);
ActionBar actionBar = getSupportActionBar();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
actionBar.setTitle("Customer Details");
name_edit = findViewById(R.id.user_name);
jacode_edit = findViewById(R.id.name_jacode);
phone_edit = findViewById(R.id.name_phone);
balance_edit = findViewById(R.id.name_balance);
paidAmount_edit = findViewById(R.id.LastPaidAmount_edit);
paidDate_edit = findViewById(R.id.lastPaidDate_edit);
rent_edit = findViewById(R.id.name_rent);
zone_edit =findViewById(R.id.name_zone);
pkgname= findViewById(R.id.name_package);
id_text = findViewById(R.id.id);
name_text= findViewById(R.id.user_name_text);
Status_text = findViewById(R.id.cid);
phone_text= findViewById(R.id.name_phone_text);
jacode_text= findViewById(R.id.name_jacode_text);
balance_text =findViewById(R.id.name_balance_text);
LastPaidAmount = findViewById(R.id.LastPaidAmount_text);
LastPaidDate = findViewById(R.id.lastPaidDate_text);
rent_text = findViewById(R.id.name_rent_text);
zone_text = findViewById(R.id.name_zone_text);
plan_text = findViewById(R.id.name_package_text);
Activation = findViewById(R.id.Activate);
Deactivation = findViewById(R.id.DeActivate);
//rent_edit = findViewById(R.id.name_rent);
//zone_edit = findViewById(R.id.name_zone);
addimgbtn = findViewById(R.id.addimgbtn);
btnEdit=findViewById(R.id.btnEdit);
btndelete = findViewById(R.id.btnDelete);
btnRecharge = findViewById(R.id.btnRecharge);
editimgbtn = findViewById(R.id.editbtnimg);
addimgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddChannel(UserDetailsActivity.this);
}
});
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTask();
}
});
btnRecharge.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View v) {
rechargeUser();
}
});
editimgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadSpinnerData();
name_edit.setVisibility(View.VISIBLE);
phone_edit.setVisibility(View.VISIBLE);
jacode_edit.setVisibility(View.VISIBLE);
balance_edit.setVisibility(View.VISIBLE);
paidAmount_edit.setVisibility(View.VISIBLE);
paidDate_edit.setVisibility(View.VISIBLE);
btndelete.setVisibility(View.VISIBLE);
btnEdit.setVisibility(View.VISIBLE);
rent_edit.setVisibility(View.VISIBLE);
zone_edit.setVisibility(View.VISIBLE);
pkgname.setVisibility(View.VISIBLE);
name_text.setVisibility(View.GONE);
phone_text.setVisibility(View.GONE);
jacode_text.setVisibility(View.GONE);
balance_text.setVisibility(View.GONE);
LastPaidAmount.setVisibility(View.GONE);
LastPaidDate.setVisibility(View.GONE);
btnRecharge.setVisibility(View.GONE);
rent_text.setVisibility(View.GONE);
zone_text.setVisibility(View.GONE);
plan_text.setVisibility(View.GONE);
// rechargebtn.setVisibility(View.GONE);
}
});
Intent intent =getIntent();
if (intent.getExtras() != null){
Contacts contacts = (Contacts) intent.getSerializableExtra("data");
id = getIntent().getStringExtra("id");
balance = getIntent().getStringExtra("balance");
Lpdate = getIntent().getStringExtra("LPDATE");
LpAmount = getIntent().getStringExtra("lpAmount");
zone = getIntent().getStringExtra("zone");
rent = getIntent().getStringExtra("rent");
Status_text.setText(contacts.getStatus());
Status = contacts.getStatus();
chId=getIntent().getStringExtra("channelID");
chName = getIntent().getStringExtra("channelName");
chMoney = getIntent().getStringExtra("channelMoney");
Toast.makeText(getApplicationContext(), chId , Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), chName , Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), chMoney , Toast.LENGTH_SHORT).show();
id_text.setText(id);
name_edit.setText(contacts.getName());
phone_edit.setText(contacts.getPhno());
jacode_edit.setText(contacts.getJacode());
balance_edit.setText(contacts.getBalance());
rent_edit.setText(rent);
zone_edit.setText(zone);
// plan_edit.setText(contacts.getCplan());
// balance_edit.setText(balance);
// paidDate_edit.setText(contacts.getPaidDate());
paidDate_edit.setText(Lpdate);
// paidAmount_edit.setText(contacts.getPaidAmount());
paidAmount_edit.setText(LpAmount);
// LastPaidDate.setText(contacts.getPaidDate());
LastPaidDate.setText(Lpdate);
//LastPaidAmount.setText(contacts.getPaidAmount());
LastPaidAmount.setText(LpAmount);
name_text.setText(contacts.getName());
phone_text.setText(contacts.getPhno());
jacode_text.setText(contacts.getJacode());
balance_text.setText(contacts.getBalance());
rent_text.setText(rent);
zone_text.setText(zone);
plan_text.setText(contacts.getCplan());
//balance_text.setText(balance);
header = name_edit.getText().toString();
}
pkgname.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
SqliteDatabase mydb = new SqliteDatabase(UserDetailsActivity.this);
SpinnerData = (String) adapterView.getItemAtPosition(i).toString();
planAmount = mydb.getPlanAmount(SpinnerData);
// Toast.makeText(getApplicationContext(),planAmount,Toast.LENGTH_SHORT).show();
rent_edit.setText(planAmount);
rent_text.setText(planAmount);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
String active ="Active";
String deac = "Deactive";
if (Status.equals(active) == true){
Activation.setVisibility(View.GONE);
Deactivation.setVisibility(View.VISIBLE);
ACTIVE_CODE =1;
}
else {
ACTIVE_CODE =2;
Activation.setVisibility(View.VISIBLE);
Deactivation.setVisibility(View.GONE);
}
Activation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
String timeStamps = simpleDateFormat.format(new Date()) ;
String statu ="Active";
String stats = "Activated On ";
String name = name_text.getText().toString();
mDatabase.statusUpdate(id ,statu);
mDatabase.statusDetails(id , name,stats,timeStamps);
Status_text.setText(statu);
Activation.setVisibility(View.GONE);
Deactivation.setVisibility(View.VISIBLE);
}
});
Deactivation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String statu ="Deactive";
String stats = "DeActivated On ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
String timeStamps = simpleDateFormat.format(new Date()) ;
String name = name_text.getText().toString();
mDatabase.statusUpdate(id ,statu);
mDatabase.statusDetails(id , name,stats,timeStamps);
Status_text.setText(statu);
Activation.setVisibility(View.VISIBLE);
Deactivation.setVisibility(View.GONE);
}
});
}
private void AddChannel(UserDetailsActivity activity) {
dialog = new Dialog(activity);
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.channel_selection);
myDB = new SqliteDatabase(this);
// myDB.getChannel();
channel_id = new ArrayList<>();
channel_name = new ArrayList<>();
channel_ntMoney = new ArrayList<>();
channel_tMoney = new ArrayList<>();
Cursor cursor = myDB.getChannel();
if (cursor.getCount()==0){
Toast.makeText(this, "No Plans Have Added yet ", Toast.LENGTH_SHORT).show();
}else {
while (cursor.moveToNext()){
channel_id.add(cursor.getString(0));
channel_name.add(cursor.getString(1));
channel_ntMoney.add(cursor.getString(2));
channel_tMoney.add(cursor.getString(3));
}
}
RecyclerView recyclerView = dialog.findViewById(R.id.channelRecyclerView);
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney);
recyclerView.setAdapter(cAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
dialog.show();
}
private void editTask() {
final String name = name_edit.getText().toString();
final String id = id_text.getText().toString();
final String rent = rent_edit.getText().toString();
final String zone = zone_edit.getText().toString();
final String ph_no = phone_edit.getText().toString();
final String jacode = jacode_edit.getText().toString();
final String balance = balance_edit.getText().toString();
final String plan = SpinnerData;
if (TextUtils.isEmpty(name)) {
Toast.makeText(getApplicationContext(),"Something Went Wrong",Toast.LENGTH_SHORT).show();
} else {
// Contacts newContact = new Contacts(Objects.requireNonNull(contacts).getId(),name, ph_no,jacode,balance);
//mDatabase.updateContacts(newContact);
mDatabase.updateContacts(id,name, ph_no,jacode,balance,rent,zone,plan);
name_edit.setText(name);name_text.setText(name);
phone_edit.setText(ph_no);phone_text.setText(ph_no);
rent_text.setText(rent);rent_edit.setText(rent);
jacode_edit.setText(jacode);jacode_text.setText(jacode);
balance_edit.setText(balance);balance_text.setText(balance);
zone_text.setText(zone);zone_edit.setText(zone);
plan_text.setText(plan);//pkgname.set(plan);
name_edit.setVisibility(View.GONE);
phone_edit.setVisibility(View.GONE);
jacode_edit.setVisibility(View.GONE);
rent_edit.setVisibility(View.GONE);
balance_edit.setVisibility(View.GONE);
paidAmount_edit.setVisibility(View.GONE);
paidDate_edit.setVisibility(View.GONE);
btndelete.setVisibility(View.GONE);
btnEdit.setVisibility(View.GONE);
zone_edit.setVisibility(View.GONE);
pkgname.setVisibility(View.GONE);
name_text.setVisibility(View.VISIBLE);
rent_text.setVisibility(View.VISIBLE);
zone_text.setVisibility(View.VISIBLE);
phone_text.setVisibility(View.VISIBLE);
jacode_text.setVisibility(View.VISIBLE);
balance_text.setVisibility(View.VISIBLE);
LastPaidAmount.setVisibility(View.VISIBLE);
LastPaidDate.setVisibility(View.VISIBLE);
btnRecharge.setVisibility(View.VISIBLE);
plan_text.setVisibility(View.VISIBLE);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void rechargeUser() {
final AlertDialog builder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.recharge,null);
builder.setTitle("Recharge " + header);
final EditText rechargeField = (EditText) dialogView.findViewById(R.id.rechargeEditText);
final Button cancel = (Button) dialogView.findViewById(R.id.btnCancelRecharge);
recharges = (Button) dialogView.findViewById(R.id.btnRechargeSucess);
recharges.setEnabled(false);
if(checkPermission(Manifest.permission.SEND_SMS))
{
recharges.setEnabled(true);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQ);
}
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Cancelled Recharge !!",Toast.LENGTH_LONG).show();
builder.dismiss();
}
});
recharges.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d1 = Integer.valueOf(rechargeField.getText().toString().trim());
d2 = Integer.valueOf(balance_edit.getText().toString().trim());
amount= d2 - d1;
data1 = String.valueOf(amount);
data2 = String.valueOf(d1);
String name = String.valueOf(name_text.getText().toString().trim());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
timeStamp = simpleDateFormat.format(new Date()) ;
String cdate = date.format(new Date());
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH,Calendar.LONG, Locale.UK);
int year = Calendar.getInstance().get(Calendar.YEAR);
String due= balance_text.getText().toString().trim();
String paid = String.valueOf(d1);
//Toast.makeText(getApplicationContext(),month,Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),String.valueOf(year),Toast.LENGTH_SHORT).show();
mDatabase.rechargeUser(id, (int) amount,d1,timeStamp);
mDatabase.InsertPaymentDetails(id,month,year,timeStamp,paid,due);
mDatabase.collectionDetails(id,name,d1,cdate,month,year);
reloadData();
sendSms();
builder.dismiss();
}
});
builder.setView(dialogView);
builder.show();
}
private void sendSms() {
String names = name_text.getText().toString();
String s1=phone_text.getText().toString();
String s2=("Hi "+names+", You have Successfully recharged ₹ " +d1 +" to your SKY VISION Cable account on "+timeStamp+". Your current balance is ₹ "+amount+" . Kindly clear your balance on time without any due. \n - Thank you! \n SKY VISION KONGAD");
if(!TextUtils.isEmpty(s1)&&!TextUtils.isEmpty(s2))
{
if(checkPermission(Manifest.permission.SEND_SMS))
{
SmsManager smsManager= SmsManager.getDefault();
ArrayList<String> part = smsManager.divideMessage(s2);
smsManager.sendMultipartTextMessage(s1,null,part,null,null);
}
else {
Toast.makeText(UserDetailsActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(UserDetailsActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
private void reloadData() {
balance_text.setText(data1);
balance_edit.setText(data1);
LastPaidAmount.setText(data2);
LastPaidDate.setText(timeStamp);
paidAmount_edit.setText(data2);
paidDate_edit.setText(timeStamp);
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.user_details, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.payment_details:
Intent intent = new Intent(this,PaymentDetailsActivity.class);
intent.putExtra("ID",id);
startActivity(intent);
break;
case R.id.WriteOff:
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Write Off?");
builder.setMessage("Are you sure you want to Write off ?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
WriteOff();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
break;
case R.id.boxDetails:
Intent boxDetails = new Intent(this,BoxDetailsActivity.class);
boxDetails.putExtra("ID",id);
startActivity(boxDetails);
break;
}
return super.onOptionsItemSelected(item);
}
private void WriteOff() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
timeStamp = simpleDateFormat.format(new Date()) ;
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH,Calendar.LONG, Locale.UK);
int year = Calendar.getInstance().get(Calendar.YEAR);
String due= balance_text.getText().toString().trim();
String paid = "Write Off";
balance_text.setText("0");
balance_edit.setText("0");
String Writeofbalance ="0";
mDatabase.writeOff(id, month , year , timeStamp , paid , due, Writeofbalance);
}
private boolean checkPermission(String sendSms) {
int checkpermission= ContextCompat.checkSelfPermission(this,sendSms);
return checkpermission== PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case SEND_SMS_PERMISSION_REQ:
if(grantResults.length>0 &&(grantResults[0]== PackageManager.PERMISSION_GRANTED))
{
btnRecharge.setEnabled(true);
}
break;
}
}
private void loadSpinnerData() {
SqliteDatabase db = new SqliteDatabase(getApplicationContext());
List<String> labels = db.getAllPlansSpinner();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,labels);
arrayAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
pkgname.setAdapter(arrayAdapter);
}
ArrayList<String> channel_id,channel_name,channel_ntMoney,channel_tMoney;
ChannelAdapter cAdapter;
public static Dialog dialog;
}
here is my ChannelAdapterActivity
ChannelAdapterActivity.Java
package com.ancorp.aplo.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ancorp.aplo.R;
import com.ancorp.aplo.activity.UserDetailsActivity;
import com.ancorp.aplo.model.Contacts;
import java.util.ArrayList;
public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.MyViewHolder> {
private Context context;
private Activity activity;
private ArrayList<Contacts> allChannels;
String id,name,money;
private ArrayList channel_id,channel_name,channel_ntMoney,channel_tMoney;
public ChannelAdapter(Activity activity, Context context, ArrayList<String> channel_id, ArrayList<String> channel_name, ArrayList<String> channel_ntMoney, ArrayList<String> channel_tMoney) {
this.context = context;
this.activity = activity;
this.channel_id = channel_id;
this.channel_name=channel_name;
this.channel_ntMoney= channel_ntMoney;
this.channel_tMoney= channel_tMoney;
}
public ChannelAdapter(Context context, ArrayList<Contacts> allChannel) {
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater .inflate(R.layout.channel_list,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int i) {
holder.channelName.setText(String.valueOf(channel_name.get(i)));
holder.channelNt.setText(String.valueOf(channel_ntMoney.get(i)));
holder.channelT.setText(String.valueOf(channel_tMoney.get(i)));
id = String.valueOf(channel_id.get(i));
name=String.valueOf(channel_name.get(i));
money = String.valueOf(channel_tMoney.get(i));
}
#Override
public int getItemCount() {
return channel_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView channelName,channelNt,channelT;
LinearLayout channelLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
channelName = itemView.findViewById(R.id.channelName);
channelNt = itemView.findViewById(R.id.ntMoney);
channelT = itemView.findViewById(R.id.tMoney);
channelLayout = itemView.findViewById(R.id.channelMainLayout);
}
}
}
Somebody please help me I am Newbie to this.

This is another method of sending data from Adapter to Activity.
Follow these steps carefully:
Create an interface with a method
public interface InterfaceTax {
public void getTaxMoney(int amount);
}
the parameters of the method should contain the data you want to send back to the activity.
Create a variable for that interface in the Adapter and add the interface to the constructor of the Adapter.
private InterfaceTax interfaceT;
public ChannelAdapter(/* other parameters */, InterfaceTax interface) {
interfaceT = interface;
}
Then in onBindViewHolder (or wherever your data is) call the method of the interface and send the data
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int i) {
money = String.valueOf(channel_tMoney.get(i));
interface.getTaxMoney(money);
}
Then in your activity implement the interface and override the method to receive data
public class UserDetailsActivity extends AppCompatActivity implements InterfaceTax {}
#Override
public void getTaxMonney(int data) {
// receive data here
}
In your AddChannel method, replace this line
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney);
with this
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney, this);
This will automatically send the data from the adapter to the activity and you can receive it in the method overridden in the activity.

Related

Why my recyclerview isn't showing any item?

I just created my recyclerview to show a cardview when I just filling the required data on AddNewTimerFragment.java. But somehow it wont show the card that contains the data that I've fill in before. I've tried to changes something, but doesn't work.
Code :
MainActivity.java
package com.mobprog.ius.dwasu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
private ArrayList<MyListDataTimer> mintervalTimeList = new ArrayList();
private RecyclerView mRecyclerView;
private alarmListAdapter mAdapter;
public boolean isFragmentAddNewAlarmDisplayed = false;
static final String STATE_FRAGMENT = "state_of_fragment";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView) findViewById(R.id.textUserName)).setText("Hello " + getSharedPreferences("Dwasu", 0).getString("user", ""));
if (getSharedPreferences("Dwasu", 0) == null || !getSharedPreferences("Dwasu", 0).contains("user")) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
// Create recycler view.
mRecyclerView = findViewById(R.id.recyclerView);
// Create an adapter and supply the data to be displayed.
mAdapter = new alarmListAdapter(getApplicationContext(), mintervalTimeList);
// Connect the adapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
if (savedInstanceState != null)
isFragmentAddNewAlarmDisplayed = savedInstanceState.getBoolean(STATE_FRAGMENT);
Button mnewReminderButton = findViewById(R.id.newReminder);
mnewReminderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(MainActivity.class.getSimpleName(),"Button Clicked");
displayFragment();
}
});
ImageButton mlogOutButton = findViewById(R.id.logOutButton);
findViewById(R.id.logOutButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSharedPreferences("Dwasu", 0).edit().clear().apply();
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
// // Get the Drawable custom_progressbar
// Drawable draw = ResourcesCompat.getDrawable(getResources(), R.drawable.progress_bar, null);
// // set the drawable as progress drawable
// ProgressBar.setProgressDrawable(draw);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the state of the fragment (true=open, false=closed).
savedInstanceState.putBoolean(STATE_FRAGMENT, isFragmentAddNewAlarmDisplayed);
super.onSaveInstanceState(savedInstanceState);
}
public void closeFragment(){
// Get the FragmentManager.
FragmentManager fragmentManager = getSupportFragmentManager();
// Check to see if the fragment is already showing.
AddNewTimerFragment simpleFragment = (AddNewTimerFragment) fragmentManager
.findFragmentById(R.id.FragmentContainer_AddNewAlarm);
if (simpleFragment != null) {
// Create and commit the transaction to remove the fragment.
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.remove(simpleFragment).commit();
}
// Set boolean flag to indicate fragment is closed.
isFragmentAddNewAlarmDisplayed = false;
}
public void displayFragment(){
AddNewTimerFragment simpleFragment = AddNewTimerFragment.newInstance();
// Get the FragmentManager and start a transaction.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// Add the SimpleFragment.
fragmentTransaction.add(R.id.FragmentContainer_AddNewAlarm,
simpleFragment).addToBackStack(null).commit();
// Set boolean flag to indicate fragment is open.
isFragmentAddNewAlarmDisplayed = true;
}
}
AddNewTimerFragment.java
package com.mobprog.ius.dwasu;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import org.apache.http.entity.mime.content.StringBody;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import static android.content.Context.MODE_PRIVATE;
public class AddNewTimerFragment extends Fragment {
Button startTime;
Button endTime;
Button meditConfirm_button;
int startHour;
int startMinute;
int endHour;
int endMinute;
int position = 1;
long totalSize = 0;
String value;
ProgressDialog progDailog;
View rootview;
private SharedPreferences mPreferences;
private String sharedPrefFile =
"com.mobprog.ius.dwasu";
public AddNewTimerFragment() {
// Required empty public constructor
}
public static AddNewTimerFragment newInstance() {
return new AddNewTimerFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_new_alarm,
container, false);
rootview = rootView;
/*Shared Pref*/
mPreferences = this.getActivity().getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
SharedPreferences.Editor mPreferencesEditor = mPreferences.edit();
ImageButton mbtnCloseFragment = rootView.findViewById(R.id.btnCloseFragment);
mbtnCloseFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).closeFragment();
}
});
// initiate the edit text
startTime = rootView.findViewById(R.id.startTimePick);
startTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
startTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
startHour = mcurrentTime.get(Calendar.HOUR);
startMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mStartTimePicker;
mStartTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedStartHour, int selectedStartMinute) {
if (selectedStartMinute == 0) {
startTime.setText(selectedStartHour + ":00");
} else if (selectedStartMinute < 10) {
if (selectedStartHour < 10) {
startTime.setText("0" + selectedStartHour + ":0" + selectedStartMinute);
}
} else {
startTime.setText(selectedStartHour + ":" + selectedStartMinute);
}
startHour = selectedStartHour;
}
}, startHour, startMinute, true);//Yes 24 hour time
mStartTimePicker.show();
}
});
endTime = rootView.findViewById(R.id.endTimePick);
endTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
endTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
endHour = mcurrentTime.get(Calendar.HOUR);
endMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mEndTimePicker;
mEndTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedEndHour, int selectedEndMinute) {
if (selectedEndMinute == 0) {
endTime.setText(selectedEndHour + ":00");
} else if (selectedEndMinute < 10) {
if (selectedEndHour < 10) {
endTime.setText("0" + selectedEndHour + ":0" + selectedEndMinute);
}
} else {
endTime.setText(selectedEndHour + ":" + selectedEndMinute);
}
endHour = selectedEndHour;
}
}, endHour, endMinute, true);//Yes 24 hour time
mEndTimePicker.show();
}
});
Spinner spinner = (Spinner) rootView.findViewById(R.id.timeIntervalPick);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.listtimer, R.layout.spinner_support);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(R.layout.spinner_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
String[] valueListTimer = getResources().getStringArray(R.array.valueListTimer);
value = valueListTimer[position];
Log.e("Value of Spinner", value);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
meditConfirm_button = rootView.findViewById(R.id.editConfirm_button);
meditConfirm_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String.valueOf(startHour);
String.valueOf(endHour);
String.valueOf(value);
new MyListDataTimer(String.valueOf(startHour),String.valueOf(endHour),String.valueOf(value),String.valueOf(position));
new UploadAlarmDataToServer().execute();
position++;
}
});
// Inflate the layout for this fragment
return rootView;
}
private class UploadAlarmDataToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progDailog = new ProgressDialog(getContext());
progDailog.setMessage("Menyimpan...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(false);
progDailog.setCanceledOnTouchOutside(false);
progDailog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
String data = null;
try {
data = sendDataTimer();
} catch (Exception e) {
e.printStackTrace();
data = "Gagal";
}
return data;
}
public String sendDataTimer() throws Exception {
URL url = new URL("https://ius.mobile.indoserver.web.id/alarmData.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
entity.addPart("startHour", new StringBody(startHour + ""));
entity.addPart("endHour", new StringBody(endHour + ""));
entity.addPart("intervalWaktu", new StringBody(value + ""));
totalSize = entity.getContentLength();
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.addRequestProperty("Content-length", totalSize + "");
con.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = con.getOutputStream();
entity.writeTo(con.getOutputStream());
os.close();
con.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
#Override
protected void onPostExecute(String result) {
progDailog.dismiss();
if (result != null) {
Log.e("UPLOAD", result);
if (result.equalsIgnoreCase("OK")) {
Toast.makeText(getContext(), "Data Alarm tersimpan", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getContext(), MainActivity.class));
}
}
super.onPostExecute(result);
}
}
}
alarmListAdapter.java
package com.mobprog.ius.dwasu;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedList;
public class alarmListAdapter extends RecyclerView.Adapter<alarmListAdapter.alarmListHolder>{
private final ArrayList<MyListDataTimer> mintervalTimeList;
private LayoutInflater mInflater;
public alarmListAdapter(Context context, ArrayList<MyListDataTimer> mintervalTimeList) {
mInflater = LayoutInflater.from(context);
this.mintervalTimeList = mintervalTimeList;
}
#Override
public alarmListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.alarm_item,
parent, false);
return new alarmListHolder(mItemView, this);
}
#Override
public void onBindViewHolder(alarmListAdapter.alarmListHolder holder, int position) {
final MyListDataTimer myListData = mintervalTimeList.get(position);
holder.mintervalTime.setText(myListData.getIntervalWaktu());
holder.mtimeWork.setText(myListData.getStartHour() +":00 - " + myListData.getEndHour() +":00");
}
#Override
public int getItemCount() {
return mintervalTimeList.size();
}
public class alarmListHolder extends RecyclerView.ViewHolder {
public TextView mintervalTime;
public TextView mtimeWork;
final alarmListAdapter mAdapter;
public alarmListHolder(View itemView, alarmListAdapter adapter) {
super(itemView);
mintervalTime = itemView.findViewById(R.id.intervalTime);
mtimeWork = itemView.findViewById(R.id.timeWork);
this.mAdapter = adapter;
}
}
}
**MyListDataTimer.java**
package com.mobprog.ius.dwasu;
public class MyListDataTimer {
private String startHour;
private String endHour;
private String intervalWaktu;
private String position;
public MyListDataTimer(String startHour, String endHour, String intervalWaktu, String position) {
this.startHour = startHour;
this.endHour = endHour;
this.intervalWaktu = intervalWaktu;
this.position = position;
}
public String getStartHour() {
return startHour;
}
public void setStartHour(String startHour) {
this.startHour = startHour;
}
public String getEndHour() {
return endHour;
}
public void setEndHour(String endHour) {
this.endHour = endHour;
}
public String getIntervalWaktu() {
return intervalWaktu;
}
public void setIntervalWaktu(String intervalWaktu) {
this.intervalWaktu = intervalWaktu;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}

Calculation using JSON Data in RecyclerView and ToggleButton

I want to do calculation using JSON Data in RecyclerView with ToggleButton. When the toggle button is checked the value should change and when its not checked the value should change again for that particular RecyclerView row. The problem is when I click the ToggleButton, 2 other RecyclerView row's ToggleButton is also checked.
CODE:
Activity
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.gridlayout.widget.GridLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class GstPlanner extends AppCompatActivity implements GstPlanAdapter.GstPlanListener{
private static final String TAG = GstPlanner.class.getSimpleName();
List<String> dateNames = new ArrayList<String>();
private List<GstPlanList> GSTLisT;
private GstPlanAdapter mAdapter;
Context context;
Spinner ret_pending_drop, state_drop, nil_drop;
String URL, URL1;
ProgressBar progress_gst, Progress_Gst_Plan;
GridLayout grid_gst;
TextView txt_retry_gst, txt_state_gst, txt_ret_type, txt_final_gst;
Button btn_retry_gst, btn_submit_state, btn_submit;
String State_GET;
RecyclerView recyclerView1;
RelativeLayout Gst_Plan_Relative;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gst_planner);
Gst_Plan_Relative = findViewById(R.id.Gst_Plan_Relative);
recyclerView1 = findViewById(R.id.Recycler_Gst_Plan);
Progress_Gst_Plan = findViewById(R.id.Progress_Gst_Plan);
btn_submit_state = findViewById(R.id.btn_submit_state);
txt_state_gst = findViewById(R.id.txt_state_gst);
txt_ret_type = findViewById(R.id.txt_ret_type);
txt_retry_gst = findViewById(R.id.txt_retry_gst);
btn_retry_gst = findViewById(R.id.btn_retry_gst);
ret_pending_drop = findViewById(R.id.ret_pending_drop);
txt_final_gst = findViewById(R.id.txt_final_gst);
state_drop = findViewById(R.id.state_drop);
btn_submit = findViewById(R.id.btn_submit);
nil_drop = findViewById(R.id.nil_drop);
grid_gst = findViewById(R.id.grid_gst);
progress_gst = findViewById(R.id.progress_gst);
GSTLisT = new ArrayList<>();
mAdapter = new GstPlanAdapter(this, GSTLisT, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView1.setLayoutManager(mLayoutManager);
recyclerView1.setItemAnimator(new DefaultItemAnimator());
recyclerView1.addItemDecoration(new MyDividerItemDecoration(this, DividerItemDecoration.VERTICAL, 36));
recyclerView1.setAdapter(mAdapter);
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL1 = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString()+"&RType="+txt_ret_type.getText().toString()+"&NIL="+nil_drop.getSelectedItem().toString()+"&Month="+ret_pending_drop.getSelectedItem().toString();
Log.e("URL1",URL1);
Progress_Gst_Plan.setVisibility(View.VISIBLE);
fetchData();
GlobalValue.getit = true;
}
});
btn_submit_state.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString();
State_GET = state_drop.getSelectedItem().toString();
btn_submit_state.setVisibility(View.INVISIBLE);
state_drop.setVisibility(View.INVISIBLE);
progress_gst.setVisibility(View.VISIBLE);
fetchMonths();
}
});
btn_retry_gst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit_state.setVisibility(View.VISIBLE);
state_drop.setVisibility(View.VISIBLE);
}
});
}
private void fetchData() {
JsonArrayRequest request = new JsonArrayRequest(URL1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response == null) {
Toast.makeText(getApplicationContext(), "Couldn't fetch the Details! Please try again.", Toast.LENGTH_LONG).show();
return;
}
Gst_Plan_Relative.setVisibility(View.VISIBLE);
Progress_Gst_Plan.setVisibility(View.INVISIBLE);
List<GstPlanList> items = new Gson().fromJson(response.toString(), new TypeToken<List<GstPlanList>>() {
}.getType());
// adding contacts to contacts list
GSTLisT.clear();
GSTLisT.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
Progress_Gst_Plan.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage() +error.getCause());
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
Gst_Plan_Relative.setVisibility(View.INVISIBLE);
}
});
APP.getInstance().addToRequestQueue(request);
}
private void fetchMonths() {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject object = jsonArray.getJSONObject(0);
JSONArray arrayContacts = object.getJSONArray("Status");
for (int i = 0; i<arrayContacts.length(); i++) {
JSONObject contactObject = arrayContacts.getJSONObject(i);
dateNames.add(contactObject.getString("Month"));
}
spinnervalue(dateNames, ret_pending_drop);
txt_state_gst.setText(State_GET);
progress_gst.setVisibility(View.INVISIBLE);
grid_gst.setVisibility(View.VISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
public void spinnervalue(List<String> value, Spinner spinner1){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, value);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void AlertDialog(String s) {
try{
AlertDialog.Builder builder1 = new AlertDialog.Builder(GstPlanner.this);
builder1.setMessage(s);
builder1.setCancelable(true);
builder1.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}catch (
WindowManager.BadTokenException ex){
ex.printStackTrace();
}
}
#Override
public void onSubTotalUpdate(int total){
txt_final_gst.setText(String.valueOf(total));
}
RecyclerView Adapter
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GstPlanAdapter extends RecyclerView.Adapter<GstPlanAdapter.MyViewHolder>
implements Filterable {
private Context context;
private List<GstPlanList> GstPlanList;
private List<GstPlanList> GstPlanListFiltered;
private GstPlanListener listener;
int totalPrice;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView ret_month, due_date, penalty_amt;
Spinner nil_ret;
ToggleButton toggleSwitch;
public MyViewHolder(View view) {
super(view);
ret_month = view.findViewById(R.id.ret_month);
due_date = view.findViewById(R.id.due_date);
penalty_amt = view.findViewById(R.id.penalty_amt);
toggleSwitch = view.findViewById(R.id.switch_gst);
}
}
public GstPlanAdapter(Context context, List<GstPlanList> BiLLList, GstPlanListener listener ) {
this.context = context;
this.listener = listener;
this.GstPlanList = BiLLList;
this.GstPlanListFiltered = BiLLList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent1, int viewType1) {
View itemView = LayoutInflater.from(parent1.getContext())
.inflate(R.layout.gst_plan_view_item_row, parent1, false);
return new MyViewHolder(itemView);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
final GstPlanList bill = GstPlanListFiltered.get(position);
holder.nil_ret.setAdapter(categoriesAdapter);
holder.ret_month.setText(bill.getMonth());
holder.due_date.setText(bill.getDate());
holder.penalty_amt.setText(bill.getPenatly().toString());
totalPrice = 0;
for (int i = 0; i < GstPlanList.size(); i++) {
totalPrice += GstPlanList.get(i).getPenatly();
countTotal(totalPrice);
}
if (GlobalValue.getit == true) {
if (bill.getNIL().equals("YES")) {
holder.toggleSwitch.setChecked(true);
GlobalValue.getit = false;
} else {
holder.toggleSwitch.setChecked(false);
GlobalValue.getit = false;
}
}
holder.toggleSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILNO().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILYES().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
if (!holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILYES().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILNO().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
}
});
}
public void countTotal(int total){
listener.onSubTotalUpdate(total);
}
#Override
public int getItemCount() {
return GstPlanListFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
GstPlanListFiltered = GstPlanList;
} else {
List<GstPlanList> filteredList = new ArrayList<>();
for (GstPlanList row : GstPlanList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getDate().toLowerCase().contains(charString.toLowerCase()) || row.getMonth().toLowerCase().contains(charString.toLowerCase()) || row.getRType().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
GstPlanListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = GstPlanListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
GstPlanListFiltered = (ArrayList<GstPlanList>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface GstPlanListener {
// void onGstPlanSelected(GstPlanList bill);
void onSubTotalUpdate(int total);
}
}
GstPlanList
public class GstPlanList {
private String RType;
private String State;
private String NILNO;
private String NILYES;
private String Month;
private String Date;
private String NIL;
private int Penatly;
private int TODATE;
public GstPlanList() {
}
public Integer getPenatly() {
return Penatly;
}
public int getTODATE() {
return TODATE;
}
public String getNIL() {
return NIL;
}
public String getRType() {
return RType;
}
public String getState() {
return State;
}
public String getNILNO() {
return NILNO;
}
public String getNILYES() {
return NILYES;
}
public String getMonth() {
return Month;
}
public String getDate() {
return Date;
}
}

How to use different background color for every listview item

Hello friends I am using a custom listview and this color picker library ' implementation 'petrov.kristiyan:colorpicker-library:1.1.5' here is link library link https://github.com/kristiyanP/colorpicker my problem is that when any user click on any particular item in the listview the color dialog is popped up so user can pick color in this dialog box and change background color of a particular item which successfully I done. But my problem is that how I can save this state for later used here is my picture you get idea what actually i want?
here my picture
here is picture of highlight two item with different color
how can save the state ?
my custom adopter code
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int selectcolor;
ArrayList<String>colors;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//check if id is exits in db
if(CheckIsDataAlreadyInDBorNot("highlight","verseid",verseid.get(position)))
{
if(verseid.get(position).equals(verseid.get(position))){
}
}
else {
}
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.linearLayout.setBackgroundColor(selectcolor);
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("highlight","verseid=?",new String[]{verseid.get(position)});
Toast.makeText(activity, "Remove highlight", Toast.LENGTH_SHORT).show();
}
});
//here color picker dialog popup for chosing color
holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("verseid",verseid.get(position));
long check=mDb.insert("highlight",null,contentValues);
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
//id get
Toast.makeText(activity, ""+verseid.get(position), Toast.LENGTH_SHORT).show();
//postion
//Toast.makeText(activity, ""+getItemId(position), Toast.LENGTH_SHORT).show();
ColorPicker colorPicker = new ColorPicker(activity);
colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
holder.linearLayout.setBackgroundColor(color);
}
#Override
public void onCancel() {
}
}).show();
return false;
}
});
/*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
return false;
}
});*/
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
//add in favourite
holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Log.d("MY_TAG","DB IS NOW "+check);
Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}else {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
/* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
*/
//My toggle button
/* holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ToggleButton addfavoruite;
private ImageView speakverse;
private LinearLayout linearLayout;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
/*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)v.findViewById(R.id.layout);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
}
I would suggest to have all your item properties in one object and add the background color to it.
When a color is picked just save it to your verse object and when view is created set it.
Also add the background to your ViewHolder.
public class Verse {
private String versenumber;
private String verseid;
private String verselist;
private String refernce;
private int backgroundColor
// Getters and setters
}
public class FullverseAdopter extends ArrayAdapter<Verse> {
private ALLVERSE activity;
private List<Verse> verse;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int selectcolor;
ArrayList<String>colors;
public FullverseAdopter(ALLVERSE context, int resource, List<Verse> verse) {
super(context, resource);
this.activity = context;
this.verse = verse;
}
// The rest of your code
}

Change colour of an item view in recycler view after comparison with its textview data

I have a RecyclerView with 'n' number of ItemViews in it. These ItemViews contain Textviews with data with are updated through Firestore.
Now I need to compare one of the value0(getexpirydate) in the Textviews with another value1(Current date). Then if value1 > value0, then change the colour of that specific Itemview to RED. else GREEN.
ContractsAdapter
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import org.w3c.dom.Text;
import java.util.Calendar;
import java.util.List;
public class ContractsAdapter extends RecyclerView.Adapter<ContractsAdapter.ContractViewHolder>{
private Context mCtx;
private List<Contracts> contractsList;
private FirebaseFirestore db;
public ContractsAdapter(Context mCtx, List<Contracts> contractsList){
this.mCtx = mCtx;
this.contractsList = contractsList;
}
#NonNull
#Override
public ContractsAdapter.ContractViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ContractViewHolder(
LayoutInflater.from(mCtx).inflate(R.layout.contract_layout, parent, false)
);
}
#Override
public void onBindViewHolder(#NonNull ContractsAdapter.ContractViewHolder holder, int position) {
Contracts contract = contractsList.get(position);
holder.contractname.setText(contract.getStationorpackagename());
holder.contractorname.setText(contract.getContractorname());
holder.dateofcommencement.setText(contract.getDateofcommnew());
holder.dateofexpiry.setText(contract.getDateofexpiry());
holder.licensefee.setText(contract.getLicensefees());
holder.contracttenure.setText(contract.getContracttenure());
holder.datesixmonths.setText(contract.getDateexpirysixmonths());
holder.dateoffloating.setText(contract.getDateofnewfloatingtender());
holder.dateofopening.setText(contract.getDateofopeningtender());
holder.dateofaward.setText(contract.getDateofletterofawardee());
holder.dateofcommnew.setText(contract.getDateofcommencementofnew());
holder.reasonsfordelay.setText(contract.getReasonsfordelay());
holder.duedatelicensefee.setText(contract.getDuedatelicensefee());
/*int po = 2;
if(po == position){
holder.itemView.setBackgroundColor(Color.RED);
} else {
holder.itemView.setBackgroundColor(Color.GREEN);
}*/
}
#Override
public int getItemCount() { return contractsList.size(); }
class ContractViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView contractname, contractorname, dateofcommencement, dateofexpiry, licensefee, contracttenure, datesixmonths;
TextView dateoffloating, dateofopening, dateofaward, dateofcommnew, reasonsfordelay;
TextView textviewtenure, sixmonths, floatingtext, opening, award, commnew, duedatelicensefee;
public ContractViewHolder(#NonNull View itemView) {
super(itemView);
contractname = itemView.findViewById(R.id.contract_name);
contractorname = itemView.findViewById(R.id.contractor_name);
dateofcommencement = itemView.findViewById(R.id.date_of_commencement);
dateofexpiry = itemView.findViewById(R.id.date_of_expiry);
licensefee = itemView.findViewById(R.id.license_fee);
contracttenure = itemView.findViewById(R.id.contract_tenure);
datesixmonths = itemView.findViewById(R.id.date_six_months);
dateoffloating = itemView.findViewById(R.id.date_floating_new);
dateofopening = itemView.findViewById(R.id.date_of_opening);
dateofaward = itemView.findViewById(R.id.letter_of_award);
dateofcommnew = itemView.findViewById(R.id.date_of_commnew);
reasonsfordelay = itemView.findViewById(R.id.reasons_delay);
duedatelicensefee = itemView.findViewById(R.id.due_license_fee);
/// Text View for explanations
textviewtenure = itemView.findViewById(R.id.textView11);
sixmonths = itemView.findViewById(R.id.textView13);
floatingtext = itemView.findViewById(R.id.textView16);
opening = itemView.findViewById(R.id.textView18);
award = itemView.findViewById(R.id.textView20);
commnew = itemView.findViewById(R.id.textView22);
//// End
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
builder.setTitle("Choose an action");
final String[] action = {"Update/Modify Contract", "Delete Contract"};
builder.setItems(action, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (action[which].equals("Update/Modify Contract")) {
Contracts contract = contractsList.get(getAdapterPosition());
Intent intent = new Intent(mCtx, Update.class);
intent.putExtra("contract", contract);
mCtx.startActivity(intent);
}
else if (action[which].equals("Delete Contract")){
Contracts contract = contractsList.get(getAdapterPosition());
Intent intent = new Intent(mCtx, Delete.class);
intent.putExtra("contract", contract);
mCtx.startActivity(intent);
}
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
return;
}
}
}
So was able to make it work by adding this before setText.
String date = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault()).format(new Date());
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
try {
Date date1 = (Date)formatter.parse(date);
Date d1 = new SimpleDateFormat("dd.MM.yyyy").parse(contract.getDateofexpiry());
if (d1.after(date1)){
holder.contractname.setTextColor(Color.GREEN);
}
} catch (ParseException e) {
e.printStackTrace();
}
#Override
public void onBindViewHolder(#NonNull ContractsAdapter.ContractViewHolder holder, int position) {
Contracts contract = contractsList.get(position);
if (contract.getCurrentDate() > contract.getDateofexpiry()) {
holder.dateofexpiry.setTextColor(Color.RED);
}
holder.dateofexpiry.setText(contract.getDateofexpiry());
}

Scrape web's infinite scrolling “load more” button using Java in Android Studio

So far I can't find an article that explains how to handle scraping infinite scrolling page in Android Studio's Java. Maybe I'm not good at searching or else.
I'm doing a news app project that will display news using web scraping technique, and can also fetch data from the next page.
More on here : How to crawl a website with multiple pages using java
But, now I'm facing a new problem because one of my news source using infinite scrolling method for their site -> https://www.gameinformer.com/news
So, is there any way I can fetch the news data from this website's load more button ?
In case anyone need my code, here it is :
GameInformer's main activity :
package com.example.user.newsapp;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class News_GameInformer extends AppCompatActivity {
Toolbar toolbar;
private ProgressDialog mProgressDialog;
private String url = "https://www.gameinformer.com/news";
private ArrayList<String> mNewsTitleList = new ArrayList<>();
private ArrayList<String> mNewsDescList = new ArrayList<>();
private ArrayList<String> mNewsDateList = new ArrayList<>();
private CardView cardView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news__game_informer);
new Description().execute();
toolbar = findViewById(R.id.toolbar_news_gameinformer);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private class Description extends AsyncTask<Void,Void,Void> {
String desc;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(News_GameInformer.this);
mProgressDialog.setTitle("Connecting to GameInformer.com");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document mNewsDocument = Jsoup.connect(url).get();
Elements mElementDataSize = mNewsDocument.select("article[class=node teaser node--type-article node--promoted node--view-mode-teaser]");
int mElementSize = mElementDataSize.size();
for (int i=0;i<mElementSize;i++) {
Elements mElementNewsTitle = mNewsDocument.select("h2[class=page-title]").select("span").eq(i);
String mNewsTitle = mElementNewsTitle.text();
Elements mElementNewsDesc = mNewsDocument.select("div[class=field field--name-field-promo-summary field--type-string field--label-hidden field__item]").eq(i);
String mNewsDesc = mElementNewsDesc.text();
Elements mElementNewsDate = mNewsDocument.select("div[class=node__submitted author-details]").select("span[class=field field--name-created field--type-created field--label-hidden]").eq(i);
String mNewsDate = mElementNewsDate.text();
mNewsTitleList.add(mNewsTitle);
mNewsDescList.add(mNewsDesc);
mNewsDateList.add(mNewsDate);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
RecyclerView mRecyclerView = findViewById(R.id.act_recyclerview_gi_news);
gameinformer_DataAdapter mDataAdapter = new gameinformer_DataAdapter(News_GameInformer.this, mNewsTitleList, mNewsDescList, mNewsDateList, cardView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mDataAdapter);
mProgressDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.gamezone) {
Intent i = new Intent(getApplicationContext(),News_GameZone.class);
startActivity(i);
} else if (id==R.id.gameinformer) {
Intent i = new Intent(getApplicationContext(),News_GameInformer.class);
startActivity(i);
} else if (id==R.id.gamespot) {
Intent i = new Intent(getApplicationContext(),News_GameSpot.class);
startActivity(i);
} else if (id==R.id.pcgamer) {
Intent i = new Intent(getApplicationContext(),News_PCGamer.class);
startActivity(i);
} else if (id==android.R.id.home) {
finish();
} else if (id==R.id.menuinfo) {
Intent i = new Intent(getApplicationContext(),Info.class);
startActivity(i);
} else if (id==R.id.menupeople) {
Intent i = new Intent(getApplicationContext(),People.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Data Adapter's code :
package com.example.user.newsapp;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class gameinformer_DataAdapter extends RecyclerView.Adapter<gameinformer_DataAdapter.MyViewHolder> {
private ArrayList<String> mNewsTitleList = new ArrayList<>();
private ArrayList<String> mNewsDescList = new ArrayList<>();
private ArrayList<String> mNewsDateList = new ArrayList<>();
private Activity mActivity;
private int lastPosition=-1;
private CardView cardView;
public gameinformer_DataAdapter (News_GameInformer activity, ArrayList<String> mNewsTitleList, ArrayList<String> mNewsDescList, ArrayList<String> mNewsDateList, CardView cardView) {
this.mActivity = activity;
this.mNewsTitleList = mNewsTitleList;
this.mNewsDescList = mNewsDescList;
this.mNewsDateList = mNewsDateList;
this.cardView = cardView;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView gameinformer_news_title, gameinformer_news_desc, gameinformer_news_date;
private CardView cardView_layout;
public MyViewHolder(View view) {
super(view);
gameinformer_news_title = view.findViewById(R.id.row_gi_news_title);
gameinformer_news_desc = view.findViewById(R.id.row_gi_news_desc);
gameinformer_news_date = view.findViewById(R.id.row_gi_news_date);
cardView_layout = view.findViewById(R.id.gi_cardview);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gameinformer_row_data,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.gameinformer_news_title.setText(mNewsTitleList.get(position));
holder.gameinformer_news_desc.setText(mNewsDescList.get(position));
holder.gameinformer_news_date.setText(mNewsDateList.get(position));
holder.cardView_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = mNewsTitleList.get(position);
Intent i = new Intent(mActivity, News_GameInformer_Webview.class);
i.putExtra("keytitle",title);
mActivity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mNewsTitleList.size();
}
}

Categories