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;
}
}
Related
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.
I've been following this tutorial: Tutorial
To make a json recyclerviewer with onclick, but i wanted to use Fragments instead of activities.
I've figured everything out until the point of the onClick.
My problem is the setOnItemClickListener is not taking my getActivity()
I've tried so much, but i just cant see the bright light.
If anyone could help me out that would be totally awesome!
Me only real problem is that the getActivity is giving a red line in the:
fNieuwsAdapter.setOnItemClickListener(getActivity());
NieuwsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import java.util.ArrayList;
public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
public static final String EXTRA_URL = "nieuwsImageUrl";
public static final String EXTRA_HEADING = "nieuwsHeading";
public static final String EXTRA_CONTENT = "nieuwsContent";
private RecyclerView fNieuwsRecyclerView;
private NieuwsAdapter fNieuwsAdapter;
private ArrayList<NieuwsItem> fNieuwsList;
private RequestQueue fNieuwsQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
fNieuwsRecyclerView.setHasFixedSize(true);
fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fNieuwsList = new ArrayList<>();
fNieuwsQueue = Volley.newRequestQueue(getActivity());
parseJSON();
return view;
}
private void parseJSON() {
String url = "urlissecretsorry<3butthejsonparsingworks";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public String nieuwsImageUrl;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
JSONArray attachArray = hit.getJSONArray("attachments");
for (int a = 0; a < attachArray.length(); a++) {
JSONObject attach = attachArray.getJSONObject(a);
nieuwsImageUrl = attach.getString("url");
}
String nieuwsHeading = hit.getString("title");
String nieuwsExcerpt = hit.getString("excerpt");
String nieuwsContent = hit.getString("content");
nieuwsExcerpt = html2text(nieuwsExcerpt);
fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
}
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
fNieuwsAdapter.setOnItemClickListener(getActivity());
fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
fNieuwsQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
NieuwsItem clickedItem = fNieuwsList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
startActivity(detailIntent);
}
public String html2text(String html) {
try {
return Jsoup.parse(html).text();
} catch (Exception ignored) {
return "";
}
}
}
NieuwsItem.java
public class NieuwsItem {
private String nieuwsImageUrl;
private String nieuwsHeading;
private String nieuwsExcerpt;
private String nieuwsContent;
public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
nieuwsImageUrl = imageUrl;
nieuwsHeading = heading;
nieuwsExcerpt = excerpt;
nieuwsContent = content;
}
public String getImageUrl(){
return nieuwsImageUrl;
}
public String getHeading(){
return nieuwsHeading;
}
public String getExcerpt(){
return nieuwsExcerpt;
}
public String getContent(){
return nieuwsContent;
}
}
NieuwsAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {
private Context NieuwsContext;
private ArrayList<NieuwsItem> NieuwsList;
private OnItemClickListener NieuwsListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
NieuwsListener = listener;
}
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
#NonNull
#Override
public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
return new NieuwsViewHolder(v);
}
#Override
public void onBindViewHolder(NieuwsViewHolder holder, int position) {
NieuwsItem currentitem = NieuwsList.get(position);
String ImageUrl = currentitem.getImageUrl();
String Heading = currentitem.getHeading();
String Excerpt = currentitem.getExcerpt();
holder.NieuwsTextViewHeading.setText(Heading);
holder.NieuwsTextViewExcerpt.setText(Excerpt);
Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
}
#Override
public int getItemCount() {
return NieuwsList.size();
}
public class NieuwsViewHolder extends RecyclerView.ViewHolder {
public ImageView NieuwsImageView;
public TextView NieuwsTextViewHeading;
public TextView NieuwsTextViewExcerpt;
public NieuwsViewHolder(#NonNull View itemView) {
super(itemView);
NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra("EXTRA_URL");
String creatorName = intent.getStringExtra("EXTRA_HEADING");
String likeCount = intent.getStringExtra("EXTRA_CONTENT");
ImageView imageView = findViewById(R.id.nieuws_detail_image);
TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
TextView textViewContent = findViewById(R.id.nieuws_detail_content);
Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
textViewHeading.setText(creatorName);
textViewContent.setText("Likes: " + likeCount);
}
}
You cant use NieuwsAdapter.setOnItemClickListener(getActivity()); , unless your activity implements OnItemClickListener interface, but im seeing that your fragment implements OnItemClickListener, so you can use the fragment instead like this :
fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);
And by the way, you are sending the data via intent with :
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
You have to get them with the same parameters (remove the ""):
String imageUrl = intent.getStringExtra(EXTRA_URL);
String creatorName = intent.getStringExtra(EXTRA_HEADING);
String likeCount = intent.getStringExtra(EXTRA_CONTENT);
Hope this helps
change
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
to
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
this.NieuwsContext = context;
this.NieuwsList = nieuwslist;
this.NieuwsListener = mOnClickListener;
}
and this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
change to
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwsListener.onItemClick(int position);
}
});
and then in fragment You can do it like this
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position)
{
//DoSomethingHere
}
});
So i developed an android news app. A spinner item is available on the toolbar and data reloads according to spinner selection. However, when the data reloads, for some of the items, it directly loads the relevant content but for some others, it loads the previously selected spinner data. Current data for the current item only shows after reloading same spinner data using the swipe refresh functionality which i had implemented. I want the correct data relevant to that selection to load the first time itself without having to refresh all the time.
Below is my MainActivity where all these functions are called.
package com.example.app.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.messaging.FirebaseMessaging;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class MainActivity extends AppCompatActivity {
String URL="url" //outputs JSON data
private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set Font
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());
myApplication = MyApplication.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
spinnerConstituencyName = new ArrayList<>();
mySpinner = findViewById(R.id.mySpinner);
prefManager = new PrefManager(MainActivity.this);
loadSpinnerData(URL);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/
if (++check > 1) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
//intent.putExtra("NAME_KEY", itemSelected);
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_video:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_favorite:
viewPager.setCurrentItem(3);
return true;
case R.id.navigation_profile:
viewPager.setCurrentItem(4);
return true;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
if (viewPager.getCurrentItem() == 1) {
toolbar.setTitle(getResources().getString(R.string.title_nav_category));
} else if (viewPager.getCurrentItem() == 2) {
toolbar.setTitle(getResources().getString(R.string.title_nav_video));
} else if (viewPager.getCurrentItem() == 3) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else if (viewPager.getCurrentItem() == 4) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else {
toolbar.setTitle(R.string.app_name);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (Config.ENABLE_RTL_MODE) {
viewPager.setRotationY(180);
}
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
// now subscribe to global topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);
} else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
Intent intent = getIntent();
final String message = intent.getStringExtra("message");
final String imageUrl = intent.getStringExtra("image");
final long nid = intent.getLongExtra("id", 0);
final String link = intent.getStringExtra("link");
if (message != null) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(mView);
final TextView notification_title = mView.findViewById(R.id.news_title);
final TextView notification_message = mView.findViewById(R.id.news_message);
final ImageView notification_image = mView.findViewById(R.id.news_image);
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
notification_title.setText(message);
notification_message.setVisibility(View.GONE);
Picasso.with(MainActivity.this)
.load(imageUrl.replace(" ", "%20"))
.placeholder(R.drawable.ic_thumbnail)
.resize(200, 200)
.centerCrop()
.into(notification_image);
alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
intent.putExtra("id", nid);
startActivity(intent);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
notification_title.setText(getResources().getString(R.string.app_name));
notification_message.setVisibility(View.VISIBLE);
notification_message.setText(message);
notification_image.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();
if (!link.equals("")) {
alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(open);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
alert.setPositiveButton(R.string.dialog_ok, null);
}
}
alert.setCancelable(false);
alert.show();
}
GDPR.updateConsentStatus(this);
}
public class MyAdapter extends FragmentPagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentRecent();
case 1:
return new FragmentCategory();
case 2:
return new FragmentVideo();
case 3:
return new FragmentFavorite();
case 4:
return new FragmentProfile();
}
return null;
}
#Override
public int getCount() {
return pager_number;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem((0), true);
} else {
exitApp();
}
}
public void exitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).equals(myString)) {
index = i;
}
}
return index;
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//TODO DONE
String name = prefManager.spinReadString();
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getString("status").equals("ok")){
JSONArray jsonArray=jsonObject.getJSONArray("constituencies");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String spinConstituency=jsonObject1.getString("constituency_name");
//TODO DONE
if (spinConstituency.equals(name))
spinConstID = jsonObject1.getInt("const_id");
spinnerConstituencyName.add(spinConstituency);
}
//TODO DONE
prefManager.writeString("" + spinConstID);
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_item, spinnerConstituencyName){
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position % 2 == 1) {
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#910D3F"));
}
else {
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#41061C"));
}
return view;
}
};
mySpinner.setPrompt("Select Your Constituency");
myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
mySpinner.setAdapter(myAdapter);
//RECEIVE DATA VIA INTENT
mySpinner.setSelection(getIndex(mySpinner, name));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
I discovered that from API level 3, one can use the onUserInteraction() on an Activity with a boolean value thereby determining the user's interaction.
Find the documentation in the link below.
http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
#Override
public void onUserInteraction() {
super.onUserInteraction();
userInteracts = true;
}
The my adjustment goes as thus in the MainActivity.java
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (IsInteracting) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
Currently I'm trying solve a issue. When I open my app, it must show the JSON output data, but the JSON take 1 - 2 seconds to finish the loading, and after that, still not updating the fragment view.
What I've tried:
1 - Using notifyDataSetChanged()
2 - Testing the app on real mobile device
3 - Search so much before create this thread.
Nothing helped me at this moment.
MainActivity.java
package etes.xdda.music;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Handler mHandler = new Handler();
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
public LinearLayout menu_dialog2;
public TextView song_detail;
public TextView time1;
public TextView time2;
private String player_status = "playing";
private ImageButton player_img;
public static SeekBar seekBar;
public static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
menu_dialog2 = findViewById(R.id.menu_dialog2);
menu_dialog2.setVisibility(View.GONE);
song_detail = findViewById(R.id.song_detail);
song_detail.setVisibility(View.GONE);
time1 = findViewById(R.id.time_1);
time2 = findViewById(R.id.time_2);
seekBar = findViewById(R.id.seekBar);
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0, 0, 0, 0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int CurrentPosition = mediaPlayer.getCurrentPosition();
int Duration = mediaPlayer.getDuration();
int progress = (getProgressPercentage(CurrentPosition, Duration));
seekBar.setProgress(progress);
String m_1;
String s_1;
//Toast.makeText(getApplicationContext(), "Current: " + CurrentPosition + " - Duration: " + mediaPlayer.getDuration(), Toast.LENGTH_LONG).show();
final int minutes_1 = (CurrentPosition / 1000) / 60;
final int seconds_1 = ((CurrentPosition / 1000) % 60);
if (minutes_1 < 10) {
m_1 = "0" + minutes_1;
} else {
m_1 = "" + minutes_1;
}
if (seconds_1 < 10) {
s_1 = "0" + seconds_1;
} else {
s_1 = "" + seconds_1;
}
time1.setText(m_1 + ":" + s_1);
String m_2;
String s_2;
final int minutes_2 = (Duration / 1000) / 60;
final int seconds_2 = ((Duration / 1000) % 60);
if (minutes_2 < 10) {
m_2 = "0" + minutes_2;
} else {
m_2 = "" + minutes_2;
}
if (seconds_2 < 10) {
s_2 = "0" + seconds_2;
} else {
s_2 = "" + seconds_2;
}
time2.setText(m_2 + ":" + s_2);
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
pauseAudio();
mHandler.removeCallbacks(mRunnable);// essencial para economizar bateria;
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
startAudio();
mHandler.postDelayed(mRunnable, 1000); // essencial para economizar bateria;
player_status = "playing";
}
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser) {
//int _progress = (getProgressPercentage(progress*10000, mediaPlayer.getDuration()));
//Toast.makeText(getApplicationContext(), String.valueOf(_progress), Toast.LENGTH_LONG).show();
//mediaPlayer.seekTo(progress);
int _progress = (progress * mediaPlayer.getDuration())/100;
mediaPlayer.seekTo(_progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
registerReceiver(broadcastReceiver, new IntentFilter("my-permission-response-action"));
registerReceiver(broadcastReceiver2, new IntentFilter("my-permission-response-quit"));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
};
BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
killMediaPlayer();
Toast.makeText(context, "OK2", Toast.LENGTH_LONG).show();
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
public void initAudio(final Context context, String url) {
if (mediaPlayer == null) {
try {
url = url.replace(" ", "%20");
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
catch (Exception e) {
Toast.makeText(context, "Falha ao iniciar o áudio", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
killMediaPlayer();
updateLayout();
clearNotificationBar();
}
});
seekBar.setMax(100);
mediaPlayer.start();
}
public void updateNotificationBar(String title, String author) {
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
Notification.MediaStyle style = new Notification.MediaStyle();
Bitmap notificationLargeIconBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_play_circle_filled_black_24dp);
Intent intent = new Intent(this, ActionReceiver.class);
intent.putExtra("action","action1");
Intent intent2 = new Intent(this, updateNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.ic_play_circle_outline_black_40dp)
.setLargeIcon(notificationLargeIconBitmap)
.setContentTitle(title)
.setContentText(author)
.setContentIntent(pendingIntent)
.setDeleteIntent(pendingIntent2)
.setColor(this.getResources().getColor(R.color.colorPrimary))
.setPriority(Notification.PRIORITY_MAX)
//.setOngoing(true) // n vai fechar a notificação
.addAction(R.drawable.ic_skip_previous_black_24dp, "Prev", pendingIntent)
.addAction(R.drawable.ic_pause_black_24dp, "PlayOrPause", pendingIntent)
.addAction(R.drawable.ic_skip_next_black_24dp, "Next", pendingIntent)
.setStyle(style);
notificationManager.notify(0, builder.build());
}
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
clearNotificationBar();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public int getProgressPercentage(long currentDuration, long totalDuration){
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 100);
long totalSeconds = (int) (totalDuration / 100);
// calculando porcentagem
percentage =(((double)currentSeconds)/totalSeconds)*100;
// retornando porcentagem
return percentage.intValue();
}
private void updateLayout() {
try {
menu_dialog.setVisibility(View.GONE);
menu_dialog2.setVisibility(View.GONE);
song_detail.setVisibility(View.GONE);
setMargins(viewPager.findViewById(R.id.viewpager_id), 0,0,0,0);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public static void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
public void clearNotificationBar() {
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
}
}
fragmentList.java
package etes.xdda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "http://ntcdn.stream/audio/";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter((MainActivity)getActivity(), lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
viewPagerAdapter.java
package etes.xdda.music;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class viewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public viewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
}
#Override
public int getCount() {
return lstTitles.size();
}
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void addFragment(Fragment fragment, String title) {
lstFragment.add(fragment);
lstTitles.add(title);
}
}
Can you help me? I really don't know what I must do to fix this problem and make the system update the view after JSON finish the loading
Solution:
Follow the below steps:
Step1:
Make this: RecyclerViewAdapter recyclerViewAdapter as a Global object so that you can access it throughout the Fragment.
Step2:
Add this line: recyclerviewadapter.notifyDataSetChanged() after the for loop in your onResponse() method.
Try it, Hopefully it should work.
Try to initialize the array list in your fragment where you have declared it
private List<mList> listContact= new ArrayList<>();
and try notifyDataSetChanged(); in your fragment too
Create an instance of your adapter in fragment and
check whether your adapter is null or not.
if(adapter != null){
adapter.notifyDataSetChanged();
} else {
adapter = new Adapter(getContext, listContact);
recyclerView.setAdapter(adapter);
}
i am working of live search with MySQL, JSON. its working fine with local array values. but not working with MySQL. my concern is when user start typing it has to search from data base and show it in listview. bellow is my Adapter for search
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import zesteve.com.myapplication.R;
import zesteve.com.myapplication.Search;
import zesteve.com.myapplication.VendProfileActivity;
/**
* Created by Ravi Shankar on 6/22/2017.
*/
public class SearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Search> vendersearchlist = null;
private ArrayList<Search> arraylist;
public SearchAdapter(Context context,
List<Search> vendersearchlist) {
mContext = context;
this.vendersearchlist = vendersearchlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Search>();
this.arraylist.addAll(vendersearchlist);
}
public class ViewHolder {
TextView id;
TextView vname;
}
#Override
public int getCount() {
return vendersearchlist.size();
}
#Override
public Search getItem(int position) {
return vendersearchlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.search_item_list, null);
// Locate the TextViews in listview_item.xml
//holder.id = (TextView) view.findViewById(R.id.id);
holder.vname = (TextView) view.findViewById(R.id.autoCompleteTextView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(Search.get(position).getRank());
holder.vname.setText(vendersearchlist.get(position).getVname());
// Listen for ListView Item Click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, VendProfileActivity.class);
// Pass all data rank
intent.putExtra("Vend_Id",
(vendersearchlist.get(position).getId()));
// Pass all data country
intent.putExtra("Vend_Name",
(vendersearchlist.get(position).getVname()));
// Pass all data population
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
vendersearchlist.clear();
if (charText.length() == 0) {
vendersearchlist.addAll(arraylist);
} else {
for (Search sl : arraylist) {
if (sl.getVname().toLowerCase(Locale.getDefault())
.contains(charText)) {
vendersearchlist.add(sl);
}
}
}
notifyDataSetChanged();
}
}
AND POJO
public class Search {
private int id;
private String vname;
public Search(int id, String vname) {
this.id = id;
this.vname = vname;
}
public int getId() {
return this.id;
}
public String getVname() {
return this.vname;
}
}
And my SearchActivity.java
import android.content.res.Resources;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import zesteve.com.myapplication.adapter.SearchAdapter;
import zesteve.com.myapplication.adapter.VenderAdapter;
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
private EditText Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
int[] id;
String[] vname;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
listview = (ListView) findViewById(R.id.listview);
Vendname = (EditText) findViewById(R.id.searchitem);
Vendname.setHint("Search "+catname+" in "+city);
//fetch data from server in json
String vsearch = Vendname.getText().toString();
prepareVender(vsearch);
// Pass results to ListViewAdapter Class
adapter = new SearchAdapter(this, vendersearchlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Locate the EditText in listview_main.xml
Vendname.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = Vendname.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void prepareVender(String sText){
AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/vend_list.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
try{
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object= array.getJSONObject(i);
Search vender = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(vender);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(sText);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Please comment if you have any doubts.
if Somebody looking for same Solution. bellow is my code
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
SearchView Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
ArrayList<Search> filteredSearchResults = new ArrayList<Search>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
progressDialog = new ProgressDialog(Search_vender.this);
progressDialog.setCancelable(false);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
//Toast.makeText(Search_vender.this,catid + city,Toast.LENGTH_LONG).show();
listview = (ListView) findViewById(R.id.listview);
Vendname = (SearchView) findViewById(R.id.searchitem);
Vendname.setQueryHint("Search "+catname+" in "+city);
Vendname.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
//Toast.makeText(Search_vender.this, String.valueOf(hasFocus),Toast.LENGTH_SHORT).show();
}
});
Vendname.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.length() > 2){
listview.setVisibility(View.VISIBLE);
GetDataVender gv = (GetDataVender) new GetDataVender().execute(newText);
}else{
listview.setVisibility(View.INVISIBLE);
}
return false;
}
});
}
public void filterSearchArray(String newText){
String pName;
filteredSearchResults.clear();
for (int i = 0; i < vendersearchlist.size(); i++)
{
pName = vendersearchlist.get(i).getVname().toLowerCase();
if ( pName.contains(newText.toLowerCase()))
{
filteredSearchResults.add(vendersearchlist.get(i));
}
}
}
class GetDataVender extends AsyncTask<String, Void, String>{
String textsearch;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading Please Wait...");
showDialog();
}
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/autosearch.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
this.textsearch = strings[0];
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
Search catagory = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(catagory);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null && result.equalsIgnoreCase("Exception Caught")){
Toast.makeText(Search_vender.this, "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
hideDialog();
}else{
filterSearchArray(textsearch);
listview.setAdapter(new SearchAdapter(Search_vender.this,filteredSearchResults));
hideDialog();
}
//hideDialog();
//adapter.notifyDataSetChanged();
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
it works when user stat search from second character.