Swipe Refresh layout - android

I have SwipeRefreshlayout.I have Implemented for recycler view.I have one problem I did not find solution from 3 days.Please help me for that,Thank you in advance for help me.Below is my activity of swiperefresh ,when I pull down list then swiperefresh progress bsr display but after applying
mSwipeRefreshView.setRefreshing(false);
condition it still show progress please below see my code for that
public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
SwipeRefreshLayout.OnRefreshListener {
RecyclerView mRecyclerView;
DashboardAdapter mAdapter;
DashboardGetSet dashboardGetSet;
ArrayList<DashboardGetSet> reportList;
ImageView imgalertIcon;
TextView txtAlertTitle, txtAlertmessage;
Dialog dialog;
Button btnCancel, btnExit;
String alertFlag = "";
String user_id;
ProgressDialog pd;
private static String LOG_TAG = "RecyclerViewActivity";
int id;
public static int totalCount;
SQLiteDatabaseHelper db;
private DrawerLayout drawerLayout;
Toolbar toolbar;
SessionManager sessionManager;
ConnectivityManager connectivityManager;
NetworkInfo networkInfo;
SwipeRefreshLayout mSwipeRefreshView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dmitdashboard);
sessionManager = new SessionManager(getApplicationContext());
init();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()== true) {
loadJSON();
} else {
showCustomDialog1();
}
mSwipeRefreshView.setOnRefreshListener(this);
mSwipeRefreshView.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshView.setRefreshing(true);
loadJSON();
}
}
);
}
private void init() {
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
pd = new ProgressDialog(this);
mAdapter = new DashboardAdapter(reportList);
db = new SQLiteDatabaseHelper(this);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mSwipeRefreshView = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshView.setColorSchemeResources(R.color.inProcess,
R.color.colorAccent,
R.color.roboto);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mSwipeRefreshView = new SwipeRefreshLayout(this);
}
#Override
protected void onResume() {
super.onResume();
mAdapter.setOnItemClickListener(new DashboardAdapter.MyClickListener(){
#Override
public void onItemClick(int position, View v) {
mSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.v("Dashboard","SwipeRefresh ");
// Start showing the refresh animation
mSwipeRefreshView.setRefreshing(true);
loadJSON();
Log.v("Dashboard","SwiperefreshLoadJson");
}
});
Log.i(LOG_TAG, " Clicked on Item " + position);
Intent intent =new Intent(Dashboard.this,CustomerDetails.class);
int i = reportList.get(position).getId();
intent.putExtra( "Value",i);
Log.d("Dashboard","Value"+i);
startActivity(intent);
}
});
}
private void loadJSON() {
mSwipeRefreshView.setRefreshing(true);
pd.setTitle("Loading...Please wait!");
pd.show();
Cursor rs = db.getUserId();
if(rs.getCount() > 0)
{
rs.moveToFirst();
do{
id = rs.getInt(rs.getColumnIndex("userid"));
}while(rs.moveToNext());
}
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Utils.url)
.build();
WebsiteService service = adapter.create(WebsiteService.class);
service.getReports( id,new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
BufferedReader reader = null;
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
output = reader.readLine();
JSONTokener tokener = new JSONTokener(output);
JSONObject json = new JSONObject(tokener);
String reports="";
JSONArray jsonArray = json.getJSONArray("reports");
reportList = new ArrayList<DashboardGetSet>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
dashboardGetSet = new DashboardGetSet();
id = jsonObj.getInt("id");
Log.d("Login Dashboard", "Id" + id);
dashboardGetSet.setId(id);
String customer_name = jsonObj.getString("customer_name");
dashboardGetSet.setCustomer_name(customer_name);
String father_name = jsonObj.getString("father_name");
dashboardGetSet.setFather_name(father_name);
String mother_name = jsonObj.getString("mother_name");
dashboardGetSet.setMother_name(mother_name);
String date_of_birth = jsonObj.getString("date_of_birth");
dashboardGetSet.setDate_of_birth(date_of_birth);
String gender = jsonObj.getString("gender");
dashboardGetSet.setGender(gender);
String mobile_no = jsonObj.getString("mobile_number");
dashboardGetSet.setMobile_no(mobile_no);
String zone = jsonObj.getString("zone");
dashboardGetSet.setZone(zone);
String address = jsonObj.getString("address");
dashboardGetSet.setAddress(address);
String zip = jsonObj.getString("zip");
dashboardGetSet.setZip(zip);
String city = jsonObj.getString("city");
dashboardGetSet.setCity(city);
String state = jsonObj.getString("state");
dashboardGetSet.setState(state);
String occuption = jsonObj.getString("occupation");
dashboardGetSet.setOccuption(occuption);
user_id = jsonObj.getString("current_user_id");
dashboardGetSet.setUser_id(user_id);
String status = jsonObj.getString("status");
dashboardGetSet.setStatus(status);
String report_status = jsonObj.getString("report_status");
dashboardGetSet.setReport_status(report_status);
String file_name = jsonObj.getString("file_name");
dashboardGetSet.setFile_name(file_name);
String saved_file_name = jsonObj.getString("saved_file_name");
dashboardGetSet.setSaved_file_name(saved_file_name);
String soft_copy_file_name = jsonObj.getString("soft_copy_file_name");
dashboardGetSet.setSaved_file_name(soft_copy_file_name);
String soft_copy_saved_file_name = jsonObj.getString("soft_copy_saved_file_name");
dashboardGetSet.setSoft_copy_saved_file_name(soft_copy_saved_file_name);
String created_at = jsonObj.getString("created_at");
dashboardGetSet.setCreated_at(created_at);
String updated_at = jsonObj.getString("updated_at");
dashboardGetSet.setUpdated_at(updated_at);
String payment_type = jsonObj.getString("payment_type");
dashboardGetSet.setPayment_type(payment_type);
String amount = jsonObj.getString("amount");
dashboardGetSet.setAmount(amount);
String counsellor_id = jsonObj.getString("counsellor_id");
dashboardGetSet.setCounsellor_id("counsellor_id");
db.insertUserDetails(id,customer_name, father_name, mother_name, date_of_birth, gender, mobile_no, counsellor_id, zone, address, zip, city, state, occuption, user_id, status, report_status, created_at, updated_at, payment_type, amount);
reportList.add(dashboardGetSet);
}
mAdapter = new DashboardAdapter(getApplication(), reportList);
mRecyclerView.setAdapter(mAdapter);
getCount();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
pd.dismiss();
mSwipeRefreshView.setRefreshing(false);
Toast.makeText(Dashboard.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
}
private void getCount() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Utils.url)
.build();
RestInterface service = adapter.create(RestInterface.class);
service.getCounts(user_id, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
BufferedReader reader = null;
String output = "";
try {
reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
output = reader.readLine();
JSONTokener tokener = new JSONTokener(output);
JSONObject json = new JSONObject(tokener);
String reports="";
int total = json.getInt("total");
Log.d("Login Dashboard", "total" + total);
dashboardGetSet = new DashboardGetSet();
dashboardGetSet.setCustomerCount(total);
totalCount = dashboardGetSet.getCustomerCount();
TextView mtotalCount = (TextView)findViewById(R.id.countText);
mtotalCount.setText("Total Reports = "+totalCount);
Log.d("Dashboard","Total Counts"+totalCount);
pd.dismiss();
if(mSwipeRefreshView.isRefreshing()){
mSwipeRefreshView.setRefreshing(false);
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
pd.dismiss();
mSwipeRefreshView.setRefreshing(false);
Toast.makeText(Dashboard.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(1,R.id.logout,1,"Logout");
item.setIcon(R.drawable.logout);
MenuItemCompat.setShowAsAction(item,MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
alertFlag = "Logout";
showCustomDialog();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
protected void showCustomDialog() {
dialog = new Dialog(Dashboard.this,
android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = dialog.getWindow();
window.setLayout(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
dialog.setCancelable(true);
dialog.setContentView(R.layout.custom_dialog);
txtAlertTitle = (TextView) dialog.findViewById(R.id.textView1);
txtAlertmessage = (TextView) dialog.findViewById(R.id.txtmessage);
btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sessionManager.logoutUser();
db.deleteUser( LogInActivity.id);
Intent intent = new Intent(Dashboard.this,
LogInActivity.class);
startActivity(intent);
finish();
}
});
btnCancel.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
if(alertFlag.equals("Logout"))
{
String uri = "#android:drawable/ic_menu_help";
txtAlertTitle.setText("Logout");
txtAlertmessage.setText("Do you want to Logout ?");
btnExit.setText("Ok");
btnCancel.setText("Cancel");
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Dashboard.this,
LogInActivity.class);
startActivity(intent);
finish();
}
});
}else if(alertFlag.equals("Back")){
String uri = "#android:drawable/ic_dialog_info";
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imgalertIcon.setImageDrawable(res);
txtAlertTitle.setText("Exit");
txtAlertmessage.setText("Do you want to Exit ?");
btnExit.setText("Ok");
btnCancel.setText("Cancel");
}
dialog.show();
}
protected void showCustomDialog1() {
dialog = new Dialog(Dashboard.this,
android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = dialog.getWindow();
window.setLayout(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
dialog.setCancelable(true);
dialog.setContentView(R.layout.custom_dialog);
txtAlertTitle = (TextView) dialog.findViewById(R.id.textView1);
txtAlertmessage = (TextView) dialog.findViewById(R.id.txtmessage);
btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnCancel.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
String uri = "#android:drawable/ic_menu_help";
txtAlertTitle.setText("Setting");
txtAlertmessage.setText("Network Not Available Do You Want To Go Network Setting ?");
btnExit.setText("OK");
btnCancel.setText("Cancel");
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
startActivity(intent);
finish();
}
});
dialog.show();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
Toast.makeText(getApplicationContext(), "Home", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.changePassword:
Intent intent =new Intent(Dashboard.this,ChangePasswordActivity.class);
startActivity(intent);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onRefresh() {
loadJSON();
}
}

Related

Search View doesn't filter ListView data with setOnQueryTextListener

My search view not working in android app, in my list view data come from mysql database. When use setOnQueryTextListener(new SearchView.OnQueryTextListener() on my search view object. filter not working.
public class Students extends AppCompatActivity {
ListView listView;
SearchView mySearachView;
StudentAdapter studentAdapter;
public static ArrayList<Student_Model> studentModelArrayList = new ArrayList<>();
String url = "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxx/androidStudentArrayList";
Student_Model student_model;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_students);
mySearachView = (SearchView)findViewById(R.id.search_student);
listView = findViewById(R.id.student_list_view);
studentAdapter = new StudentAdapter(this, studentModelArrayList);
listView.setAdapter(studentAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
ProgressDialog progressDialog = new ProgressDialog(view.getContext());
CharSequence[] dialogItem = { "See Details"," Update Student Details" , "Update Image"};
builder.setTitle(studentModelArrayList.get(position).getName());
builder.setItems(dialogItem, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
switch (i){
case 0:
startActivity(new Intent(getApplicationContext(),StudentDetails.class).putExtra("position", position));
break;
case 1:
startActivity(new Intent(getApplicationContext(),Student_Edit.class).putExtra("position", position));
break;
case 2:
startActivity(new Intent(getApplicationContext(),Student_Image_Update.class).putExtra("position", position));
break;
}}});
builder.create().show();}
});
retrieveData();
mySearachView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
studentAdapter.getFilter().filter(s);
return false;
}
});
}
public void retrieveData(){
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
studentModelArrayList.clear();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if(success.equals("1")){
for(int i = 0; i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String img;
String image = object.getString("img");
if(image.equals("")){
img = "https://blueboyscricket.com/img/android_placeholder.png";
}else{
img = "https://blueboyscricket.com/images/"+image;
}
String id = object.getString("id");
String name = object.getString("cnd_name");
String father_name = object.getString("father_name");
String mobile_no = object.getString("contact_no_primary");
String doj = object.getString("doj");
String mother_name = object.getString("mother_name");
String dob = object.getString("dob");
String status = object.getString("status");
student_model = new Student_Model(id,name,father_name,doj,mobile_no,img,status,mother_name,dob);
studentModelArrayList.add(student_model);
studentAdapter.notifyDataSetChanged();
}
}else{}
} catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Students.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}

How Do We Set id For Data That Showed With Volley Json Array Request

I have some problem about setting and getting id from data that showed with volley JSon array request.
I've tried to do this, but it fail.
ChildTidur.java
public class ChildTidur extends AppCompatActivity implements TidurAdapter.ContactsAdapterListener {
private static final String TAG = ChildTidur.class.getSimpleName();
private RecyclerView recyclerView;
private List<Story> storyList;
private TidurAdapter mAdapter;
private SearchView searchView;
private TextView noFavtsTV;
private AppPreferences appPreferences;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 2000;
public static final int READ_TIMEOUT = 2000;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
// url to fetch contacts json
private static final String URL = "https://api.kafeinkode.com/childtidur.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child_tidur);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
//toolbar logo and desc
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbarTidur);
setSupportActionBar(topToolBar); //munculkan menu ke toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //this line shows back button
recyclerView = findViewById(R.id.recycler_view);
noFavtsTV = findViewById(R.id.no_favt_text);
storyList = new ArrayList<>();
mAdapter = new TidurAdapter(this, storyList, this, appPreferences);
// white background notification bar
whiteNotificationBar(recyclerView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new TidurDekor(this, DividerItemDecoration.VERTICAL, 36));
recyclerView.setAdapter(mAdapter);
//Make call to AsyncTask
new AsyncLogin().execute();
//Get radio button value
LoadPreferences();
} //OnCreate
private void showNoFavtText(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
private void LoadPreferences(){
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.activity_settings, null,false);
RadioGroup radioGroup = (RadioGroup)contentView.findViewById(R.id.radioSex);
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
RadioGroup genderGroup = (RadioGroup) contentView.findViewById(R.id.radioSex);
RadioButton male = (RadioButton) contentView.findViewById(R.id.theme1);
RadioButton female = (RadioButton) contentView.findViewById(R.id.theme2);
if (genderGroup.getCheckedRadioButtonId() == -1) {
Toolbar tb = (Toolbar) findViewById(R.id.toolbarTidur);
tb.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
else {
if (male.isChecked()) { // one of the radio buttons is checked
Toolbar tb1 = (Toolbar) findViewById(R.id.toolbarTidur);
tb1.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
else if (female.isChecked()) {
Toolbar tb2 = (Toolbar) findViewById(R.id.toolbarTidur);
tb2.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
}
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(ChildTidur.this);
HttpURLConnection conn;
java.net.URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFavtText(false);
pdLoading.setMessage("\tMencoba terhubung ke internet...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("https://api.kafeinkode.com/childtidur.json");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
/**
* fetches json by making http calls
*/
protected void onPostExecute(String result) {
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pdLoading.dismiss();
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {
}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdLoading.dismiss();
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
showNoFavtText(true);
}
});
TidurSearch.getInstance().addToRequestQueue(request);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_tidur, menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable_tidur configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search2).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search2) {
return true;
}
//Menu
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
else
if (id == R.id.about_us) {
startActivity(new Intent(this, AboutUs.class));
return true;
}
else
if (id == R.id.favlist) {
startActivity(new Intent(this, ShowFavouriteList.class));
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close search view on back button pressed
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
private void whiteNotificationBar(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
getWindow().setStatusBarColor(Color.WHITE);
}
}
#Override
public void onContactSelected(Story story) {
Toast.makeText(getApplicationContext(), "Selected: " + story.getName(), Toast.LENGTH_LONG).show();
}
}
TidurAdapter.java
public void onClick(View view) {
// Another problem lays here when I get id of data
Story story = storyList.get(getLayoutPosition());
int ambilId = Integer.parseInt(story.getIdStory());
if ( 0 == ambilId ) {
Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
view.getContext().startActivity(myIntent);
}
else if ( 1 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
view.getContext().startActivity(myIntent);
}
else if ( 2 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
view.getContext().startActivity(myIntent);
}
}
This is a full code:
Story.java
public Story(){}
String name;
String nomor;
private String idStory;
private int isLiked;
public String getName() {
return name;
}
public String getNomor() { return nomor; }
public void setIdStory(String isStory) {
this.idStory = isStory;
}
public String getIdStory() {
return idStory;
}
public void setIsLiked(int isLiked) {
this.isLiked = isLiked;
}
public int getIsLiked() {
return isLiked;
}
}
ChildTidur.java
/**
* fetches json by making http calls
*/
protected void onPostExecute(String result) {
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pdLoading.dismiss();
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {
}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdLoading.dismiss();
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
showNoFavtText(true);
}
});
TidurSearch.getInstance().addToRequestQueue(request);
}
}
TidurAdapter.java
public class TidurAdapter extends RecyclerView.Adapter<TidurAdapter.TidurViewHolder> implements Filterable {
private Context context;
private List<Story> storyList;
private List<Story> storyListFiltered;
private ContactsAdapterListener listener;
private int changedItemPosition;
public boolean isLiked;
private AppPreferences appPreferences;
Boolean checked = false;
public TidurAdapter(Context context, List<Story> storyList, ContactsAdapterListener listener, AppPreferences appPreferences) {
this.context = context;
this.listener = listener;
this.storyList = storyList;
this.storyListFiltered = storyList;
this.appPreferences = appPreferences;
}
#Override
public TidurViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_row_item_tidur, parent, false);
return new TidurViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TidurViewHolder holder, int position) {
final Story story = storyListFiltered.get(position);
holder.name.setText(story.getName());
holder.nomor.setText(story.getNomor());
holder.setViewData(storyList.get(position), holder.getAdapterPosition());
}
#Override
public int getItemCount() {
return storyListFiltered.size();
}
public interface ContactsAdapterListener {
void onContactSelected(Story story);
}
//ViewHolder
public class TidurViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView nomor;
public ImageView mFavorite;
private CheckBox likeCheckBox;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
public TidurViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
nomor = view.findViewById(R.id.nomor);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get id of data
Story story = storyList.get(getLayoutPosition());
int ambilId = Integer.parseInt(story.getIdStory());
if ( 0 == ambilId ) {
Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
view.getContext().startActivity(myIntent);
}
else if ( 1 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
view.getContext().startActivity(myIntent);
}
else if ( 2 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
view.getContext().startActivity(myIntent);
}
}
});
//Get radio button value
LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View cV = inflater.inflate(R.layout.activity_settings, null,false);
RadioGroup radioGroup = (RadioGroup)cV.findViewById(R.id.radioSex);
SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("MY_SHARED_PREF", Activity.MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
RadioGroup genderGroup = (RadioGroup) cV.findViewById(R.id.radioSex);
RadioButton male = (RadioButton) cV.findViewById(R.id.theme1);
RadioButton female = (RadioButton) cV.findViewById(R.id.theme2);
if (genderGroup.getCheckedRadioButtonId() == -1) {
nomor.setBackgroundColor(view.getResources().getColor(R.color.colorPrimaryDark));
} else {
if (male.isChecked()) { // one of the radio buttons is checked
nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable));
}
else if (female.isChecked()) {
nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable_red));
}
}
} //TidurViewHolder(View view)
public void setViewData(final Story story, final int adapterPosition) {
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(true);
}
else {
likeCheckBox.setChecked(false);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
isLiked = true;
updateLikes();
appPreferences.saveFavouriteCard(story);
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
else {
isLiked = false;
updateLikes();
appPreferences.deleteCard(story.getIdStory());
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
}
}
}
});
} //setviewdata
public void updateLikes() {
if (isLiked && storyList.get(changedItemPosition).getIsLiked() == 0) { //jika dilakukan like (pada posisi hati kosong) di halaman home
storyList.get(changedItemPosition).setIsLiked(1); //maka jadikan hati berwarna merah di halaman favourite list
notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
}
else if (!isLiked && storyList.get(changedItemPosition).getIsLiked() == 1) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman home
storyList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
}
} //updateLikes
}//Class TidurViewHolder
}
The error result is, it is showing null... Which mean no ID that can be obtained.
In your for loop you are not setting id of your List, but your new Story.
Instead of:
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
Use this:
for (int i=0; i<storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i));
}
Also because your index i=0 starts from zero, you should change for loop index i to start from 1 like this:
for (int i=1; i<=storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i));
}
Check this main activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
private ArrayList<Story> storyList;
// url to fetch contacts json
private static final String URL = "https://api.kafeinkode.com/childtidur.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storyList = new ArrayList<>();
//Fetch JSON data
fetchData();
}
private void fetchData(){
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
for (int i=0; i<storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i + 1));
}
Log.d("StoryLid: ", storyList.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
}
});
VolleyService.getInstance(this).getRequestQueue().add(request);
}
}
As a result you have response:

How to refresh Fragment from different java file?

Here's my java from 'different java file' :
public class MainPage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ArrayList<HashMap<String, String>> Item_List;
TabLayout tabLayout;
ViewPageAdapter viewPageAdapter;
ViewPager viewPager;
ImageView pfp;
ProgressDialog PD_three;
Bitmap bitmap;
TextView usernameToolbar;
Intent postActivity;
Bitmap cropImg;
private int PICK_IMAGE_REQUEST = 1;
private String KEY_IMAGE = "ProfilePicture";
private String KEY_NAME = "Name";
private String KEY_USERTOKEN = "UserToken";
private String UserToken;
final int CROP_PIC_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
initTypeface();
PD_three = new ProgressDialog(this);
PD_three.setCancelable(false);
PD_three.setTitle("Please Wait...");
PD_three.setMessage("Retrieving Data from Database...");
getProfileInfo();
String username = getIntent().getStringExtra("Username");
TextView tv = (TextView) findViewById(R.id.usernameND);
tv.setText(username);
//id's
pfp = (ImageView) findViewById(R.id.imageView_one);
//SearchIntent
Intent searchI = getIntent();
if (Intent.ACTION_SEARCH.equals(searchI.getAction())) {
String query = searchI.getStringExtra(SearchManager.QUERY);
Toast.makeText(MainPage.this, query, Toast.LENGTH_SHORT).show();
}
//Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
//Tabs
tabLayout = (TabLayout) findViewById(R.id.tablayout_two);
viewPager = (ViewPager) findViewById(R.id.viewPager_two);
viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPageAdapter.addFragments(new FeedFragment(), "Feed");
viewPageAdapter.addFragments(new MessagesFragment(), "Messages");
viewPageAdapter.addFragments(new NotificationsFragment(), "Notifications");
viewPager.setAdapter(viewPageAdapter);
tabLayout.setupWithViewPager(viewPager);
//NavigationDrawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.profile) {
Intent i = new Intent(this, Profile.class);
startActivity(i);
} else if (id == R.id.whatshot) {
Intent i = new Intent(this, WhatsHot.class);
startActivity(i);
} else if (id == R.id.trending) {
Intent i = new Intent(this, Trending.class);
startActivity(i);
} else if (id == R.id.radioplayer) {
Intent i = new Intent(this, Radio.class);
startActivity(i);
} else if (id == R.id.musicplayer) {
Intent i = new Intent(this, MusicPlayer.class);
startActivity(i);
} else if (id == R.id.settings) {
Intent i = new Intent(this, Settings.class);
startActivity(i);
} else if (id == R.id.info) {
Intent i = new Intent(this, Info.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.search_view).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
//ImageInfo
//Typeface
private void initTypeface() {
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Amble-Regular.ttf");
TextView text = (TextView) findViewById(R.id.toolbarTitle);
text.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Amble-Regular.ttf");
text = (TextView) findViewById(R.id.usernameND);
text.setTypeface(myTypeface);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v(MainPage.class.getSimpleName(), "hey=" + requestCode + resultCode);
if (resultCode == CROP_PIC_REQUEST_CODE || resultCode == 2 || resultCode == -1) {
if (requestCode == CROP_PIC_REQUEST_CODE) {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap image = extras.getParcelable("data");
pfp.setImageBitmap(image);
UploadImage();
bitmap = image;
}
}
}
}
private void getProfileInfo() {
Intent I = getIntent();
String Uname = I.getStringExtra("Username");
final String Username = Uname.replaceAll("\\s", "");
RequestQueue queue = Volley.newRequestQueue(MainPage.this);
PD_three.show();
String UPLOAD_URL = "http://10.0.0.177/Echo/ServerFilesApp/GetProfileInfo.php?Username=" + Username;
StringRequest stringRequest = new StringRequest(Request.Method.GET, UPLOAD_URL, new Response.Listener<String>() {
#Override
public Bitmap onResponse(String response) {
PD_three.dismiss();
UserToken = response;
getProfilePicture();
return null;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD_three.dismiss();
Toast.makeText(MainPage.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
queue.add(stringRequest);
}
private void getProfilePicture() {
PD_three.show();
RequestQueue queue = Volley.newRequestQueue(MainPage.this);
String IMAGE_URL = "http://10.0.0.177/Echo/Users/" + UserToken + "/ProfilePicture.jpg";
pfp = (ImageView) findViewById(R.id.imageView_one);
ImageRequest request = new ImageRequest(IMAGE_URL,
new Response.Listener<Bitmap>() {
#Override
public Bitmap onResponse(Bitmap bitmap) {
cropImg = Bitmap.createBitmap(bitmap, 0, 0, 99, 99);
pfp.setImageBitmap(cropImg);
PD_three.dismiss();
return cropImg;
}
}, 0, 0, ImageView.ScaleType.FIT_CENTER, Bitmap.Config.RGB_565,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
PD_three.dismiss();
pfp.setImageResource(R.drawable.ic_user_b);
Toast.makeText(MainPage.this, "Error on retrieving profile pic.", Toast.LENGTH_LONG).show();
}
});
queue.add(request);
}
private void UploadImage() {
RequestQueue queue = Volley.newRequestQueue(MainPage.this);
String UPLOAD_URL = "http://10.0.0.177/Echo/ServerFilesApp/UpdateProfilePicture.php";
PD_three.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public Bitmap onResponse(String response) {
// getProfilePicture();
PD_three.dismiss();
Log.v(MainPage.class.getSimpleName(), "hey=hey");
getProfilePicture();
return null;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD_three.dismiss();
Toast.makeText(MainPage.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String Image = getImageUri(bitmap);
String Name = UserToken + "/ProfilePicture";
Map<String, String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, Image);
params.put(KEY_NAME, Name);
params.put(KEY_USERTOKEN, UserToken);
return params;
}
};
queue.add(stringRequest);
}
public String getImageUri(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void postClick(View view) {
Intent I = getIntent();
String Uname = I.getStringExtra("Username");
final String Username = Uname.replaceAll("\\s", "");
//COMPRESS PFP
ByteArrayOutputStream stream = new ByteArrayOutputStream();
cropImg.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
postActivity = new Intent(MainPage.this, PostFragment.class);
postActivity.putExtra("UserToken", UserToken);
postActivity.putExtra("Username", Username);
postActivity.putExtra("profilePicture", byteArray);
MainPage.this.startActivity(postActivity);
//MainPage.this.overridePendingTransition(R.anim.slide_down, R.anim.slide_up);
}
public void onPfpClick(View view) {
Intent cropImage = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cropImage.putExtra("crop", "true");
cropImage.putExtra("aspectX", 1);
cropImage.putExtra("aspectY", 1);
cropImage.putExtra("outputX", 100);
cropImage.putExtra("outputY", 100);
cropImage.putExtra("return-data", true);
setResult(RESULT_OK, cropImage);
startActivityForResult(cropImage, CROP_PIC_REQUEST_CODE);
}
private String Username() {
String Username = getIntent().getStringExtra("Username");
return Username;
}
}
Here's my fragment java code:
public class FeedFragment extends Fragment {
private static final String TAG = FeedFragment.class.getSimpleName();
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
String UsernamePast;
String UserTokenPast;
Cache cache;
Entry entry;
String URL_FEED;
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_feed, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView listView = (ListView) getView().findViewById(R.id.FeedContentList);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getContext(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
cache = AppController.getInstance().getRequestQueue().getCache();
URL_FEED = "http://10.0.0.177/Echo/ServerFilesApp/feed.json";
entry = cache.get(URL_FEED);
getFeedContent();
}
public void getFeedContent() {
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public Bitmap onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
Log.v(TAG, "hey=" + "heu");
if (response != null) {
parseJsonFeed(response);
}
return null;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json response and passing the data to feed view list adapter
*/
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImage(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePicture(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedURL = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setURL(feedURL);
item.setLitBackground(R.drawable.fire);
feedItems.add(item);
}
FeedItem item2 = new FeedItem();
item2.setId(0);
item2.setName("SORRY");
// Image might be null sometimes
item2.setImage(null);
item2.setStatus("This Is Everything there is for Now. Refresh to get More Content");
item2.setProfilePicture(null);
item2.setTimeStamp(null);
item2.setURL(null);
feedItems.add(item2);
// notify data changes to list adapter
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResume() {
super.onResume();
getFeedContent();
}
#Override
public void onPause() {
super.onPause();
cache.clear();
}
}
To go more in depth, what I'm trying to figure out is how can I refresh a fragment from a different java file?
Our objective is to have feed like Facebook but it doesn't load the posts we post. How will that be possible? (preferably using Google Volley request, if possible)
If different java file is the container activity of fragment, then that activity must have the reference of that particular fragment, you can control the fragment with this instance easily. But make sure that when when you will show this fragment, then the instance you used in activity, that instance is used for showing otherwise what you have changed in the fragment you won't get that update. your code is for fragments:
tabLayout = (TabLayout) findViewById(R.id.tablayout_two);
viewPager = (ViewPager) findViewById(R.id.viewPager_two);
viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPageAdapter.addFragments(new FeedFragment(), "Feed");
viewPageAdapter.addFragments(new MessagesFragment(), "Messages");
viewPageAdapter.addFragments(new NotificationsFragment(), "Notifications");
viewPager.setAdapter(viewPageAdapter);
tabLayout.setupWithViewPager(viewPager);
Here new instance of fragments are being created every time. According to your demands this should be:
FeedFragment feedFragment = new FeedFragment();
MessagesFragment messagesFragment = new MessagesFragment();
NotificationFragment notifyFragment = new NotificationFragment();
tabLayout = (TabLayout) findViewById(R.id.tablayout_two);
viewPager = (ViewPager) findViewById(R.id.viewPager_two);
viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPageAdapter.addFragments(feedFragment, "Feed");
viewPageAdapter.addFragments(messagesFragment, "Messages");
viewPageAdapter.addFragments(notifyFragment, "Notifications");
viewPager.setAdapter(viewPageAdapter);
tabLayout.setupWithViewPager(viewPager);
Now with the references of fragment, you can do whatever you want to the fragment. Here in the above code snippet the references are local variable, you can make it global and access this reference from wherever you want in the activity.
Still if you have any question, let me know.

ViewPager have stuck while Swiping

I've 11 fragments in my view pager and 10 fragments have network call.The application is running and data is loading.but while swiping fragments,it have stuck.how can i make my swiping smoother? here is my fragment code.
public class Entertainment extends Fragment implements URL,Constants {
Button malayalam_btn, tamil_btn, hindi_btn, english_btn;
private GridLayoutManager malayalam, tamil, hindi, english;
RecyclerView malayalam_rv, tamil_rv, hindi_rv, english_rv;
TextView malayalam_tv, tamil_tv, hindi_tv, english_tv;
MalayalamAdapter malayalamAdapter;
TamilAdapter tamilAdapter;
HindiAdapter hindiAdapter;
EnglishAdapter englishAdapter;
public static ArrayList<EntertainmentModel> malayalam_list;
public static ArrayList<EntertainmentModel> tamil_list;
public static ArrayList<EntertainmentModel> hindi_list;
public static ArrayList<EntertainmentModel> english_list;
public static ArrayList<EntertainmentModel> entertainment_modal_list;
ProgressBar progressBar;
FetchData fetchData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_entertainment, null);
Log.i("riyas", "oncreateview called in Entertainment");
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
String font_path_English = "fonts/DIN Alternate Bold.ttf";
Typeface fontEnglish = Typeface.createFromAsset(getActivity().getAssets(), font_path_English);
myClickHandler();
malayalam_tv = (TextView) view.findViewById(R.id.malayalam_tv);
tamil_tv = (TextView) view.findViewById(R.id.tamil_tv);
hindi_tv = (TextView) view.findViewById(R.id.hindi_tv);
english_tv = (TextView) view.findViewById(R.id.english_tv);
malayalam_btn=(Button)view.findViewById(R.id.button6);
malayalam_btn.setVisibility(GONE);
tamil_btn=(Button)view.findViewById(R.id.button7);
tamil_btn.setVisibility(GONE);
hindi_btn=(Button)view.findViewById(R.id.button8);
hindi_btn.setVisibility(GONE);
english_btn=(Button)view.findViewById(R.id.button9);
english_btn.setVisibility(GONE);
malayalam_tv.setTypeface(fontEnglish);
tamil_tv.setTypeface(fontEnglish);
hindi_tv.setTypeface(fontEnglish);
english_tv.setTypeface(fontEnglish);
malayalam_rv = (RecyclerView) view.findViewById(R.id.malayalam);
malayalam = new GridLayoutManager(getActivity(), 2);
malayalam_rv.setHasFixedSize(true);
malayalam_rv.setLayoutManager(malayalam);
tamil_rv = (RecyclerView) view.findViewById(R.id.tamil);
tamil = new GridLayoutManager(getActivity(), 1);
tamil_rv.setHasFixedSize(true);
tamil_rv.setLayoutManager(tamil);
hindi_rv = (RecyclerView) view.findViewById(R.id.hindi);
hindi = new GridLayoutManager(getActivity(), 2);
hindi_rv.setHasFixedSize(true);
hindi_rv.setLayoutManager(hindi);
english_rv = (RecyclerView) view.findViewById(R.id.english);
english = new GridLayoutManager(getActivity(), 1);
english_rv.setHasFixedSize(true);
english_rv.setLayoutManager(english);
return view;
}
public void myClickHandler() {
String Url = ENTERTAINMENT_API;
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new Network().execute(Url);
} else {
Toast.makeText(getActivity(), "No Network connection Available", Toast.LENGTH_SHORT).show();
}
}
private class Network extends AsyncTask<String, Void, Void> implements NetworkOperation {
#Override
protected Void doInBackground(String... params) {
fetchData = new FetchData(this, getActivity(), params[0]);
fetchData.fromServer();
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressBar.setVisibility(View.GONE);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void JsonParse(JSONObject jsonObject) {
malayalam_list = new ArrayList<EntertainmentModel>();
tamil_list = new ArrayList<EntertainmentModel>();
hindi_list = new ArrayList<EntertainmentModel>();
english_list = new ArrayList<EntertainmentModel>();
try {
JSONArray section = jsonObject.getJSONArray("sections");
for (int i = 0; i < section.length(); i++) {
JSONObject subitem = section.getJSONObject(i);
String name = subitem.getString(HOME_NAME);
String cat_id = subitem.getString(CAT_ID);
String style = subitem.getString(STYLE);
String seeMore = subitem.getString(HOME_SEEMORE);
String lm = subitem.getString("lm");
String identifier = subitem.getString("identifier");
JSONArray News = subitem.getJSONArray(HOME_NEWS);
for (int j = 0; j < News.length(); j++) {
entertainment_modal_list = new ArrayList<EntertainmentModel>();
EntertainmentModel ent_modalobj = null;
JSONObject newsObject = News.getJSONObject(j);
String ID = newsObject.getString(HOME_ID);
String post_title = newsObject.getString(HOME_POST_TITLE);
String post_date = newsObject.getString(HOME_POST_DATE);
String post_time = newsObject.getString(HOME_POST_TIME);
String is_video = newsObject.getString(ISVIDEO);
String medium = newsObject.getString(HOME_MEDIUM);
String large = newsObject.getString(HOME_LARGE);
ent_modalobj = new EntertainmentModel(name, cat_id, style, seeMore, lm, identifier, ID, post_title, post_date, is_video, post_time, medium, large);
entertainment_modal_list.add(ent_modalobj);
for (int m = 0; m < entertainment_modal_list.size(); m++) {
String news_type = entertainment_modal_list.get(m).getName();
switch (news_type) {
case MALAYALAM:
malayalam_list.add(ent_modalobj);
malayalam_tv.setText(malayalam_list.get(m).getName().toUpperCase());
malayalam_tv.setBackgroundResource(R.color.violet);
final String id=malayalam_list.get(m).getCat_id().toString();
malayalam_btn.setVisibility(View.VISIBLE);
malayalam_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), More.class);
intent.putExtra("cat", id);
intent.putExtra("title", "MALAYALAM");
getContext().startActivity(intent);
}
});
break;
case TAMIL:
tamil_list.add(ent_modalobj);
tamil_tv.setText(tamil_list.get(m).getName().toUpperCase());
tamil_tv.setBackgroundResource(R.color.violet);
final String idt=tamil_list.get(m).getCat_id().toString();
tamil_btn.setVisibility(View.VISIBLE);
tamil_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), More.class);
intent.putExtra("cat", idt);
intent.putExtra("title", "TAMIL");
getContext().startActivity(intent);
}
});
break;
case HINDI:
hindi_list.add(ent_modalobj);
hindi_tv.setText(hindi_list.get(m).getName().toUpperCase());
hindi_tv.setBackgroundResource(R.color.violet);
final String idh=hindi_list.get(m).getCat_id().toString();
hindi_btn.setVisibility(View.VISIBLE);
hindi_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), More.class);
intent.putExtra("cat", idh);
intent.putExtra("title", "HINDI");
getContext().startActivity(intent);
}
});
break;
case ENGLISH:
english_list.add(ent_modalobj);
english_tv.setText(english_list.get(m).getName().toUpperCase());
english_tv.setBackgroundResource(R.color.violet);
final String ide=english_list.get(m).getCat_id().toString();
english_btn.setVisibility(View.VISIBLE);
english_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), More.class);
intent.putExtra("cat", ide);
intent.putExtra("title", "ENGLISH");
getContext().startActivity(intent);
}
});
break;
}
}
}
}
} catch (JSONException | OutOfMemoryError e) {
e.printStackTrace();
}
malayalamAdapter = new MalayalamAdapter(getActivity(), malayalam_list);
malayalam_rv.setAdapter(malayalamAdapter);
tamilAdapter = new TamilAdapter(getActivity(), tamil_list);
tamil_rv.setAdapter(tamilAdapter);
hindiAdapter = new HindiAdapter(getActivity(), hindi_list);
hindi_rv.setAdapter(hindiAdapter);
englishAdapter = new EnglishAdapter(getActivity(), english_list);
english_rv.setAdapter(englishAdapter);
progressBar.setVisibility(View.GONE);
}
}
I tried the following:
viewPager.setOffscreenPageLimit(4);
2.Log.i("oncreate is called or not")

onBackPressed makes the app to crash

I got one activity with several fragments, i use the intent to open the activity, all runs correctly, but when i press the android back button to return to the previous activity makes the app to crash, when i click in the home button the app runs normally... i will post the code to see whats is happening...thanks in advice
The Activity who crashs when the android button is pressed
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_os);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle id = getIntent().getExtras();
String get = id.getString("id");
String coiso = id.getString("versao");
String tab = id.getString("tab");
int position = Integer.parseInt(tab);
int intOS = Integer.parseInt(get);
int Versao = Integer.parseInt(coiso);
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.selector);
}
});
tabs.setViewPager(pager);
pager.setCurrentItem(position);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(OS.this, MainActivity.class);
intent.putExtra("position", 2);
startActivity(intent);
}
The fragment who open this activity
public static VersaoOrdemServico newInstance(String param1) {
VersaoOrdemServico fragment = new VersaoOrdemServico();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
public VersaoOrdemServico() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View tela = inflater.inflate(R.layout.fragment_versao_ordem_servico, container, false);
final ListView lView = (ListView)tela.findViewById(R.id.ListaVersaoOS);
adpt = new OSVersaoListAdapter(new ArrayList<OSID>(), getActivity());
lView.setAdapter(adpt);
lView.setEmptyView(tela.findViewById(android.R.id.empty));
Bundle id = getArguments();
String get = id.getString("id");
getActivity().setTitle("Versões da OS Nº"+get);
int itinerario = Integer.parseInt(get);
if (isOnline()) {
item = new OSID(itinerario);
(new Carregadados()).execute();
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adpt.getItem(position);
String titulo = ((TextView) view.findViewById(R.id.IDOS)).getText().toString();
String versao = ((TextView) view.findViewById(R.id.textoosfunc)).getText().toString();
Intent intent = new Intent(getActivity(), OS.class);
String IDrestante = titulo.replace("OS Nº ", "");
String Versao = versao.replace("Versão: ", "");
intent.putExtra("id", IDrestante);
intent.putExtra("versao", Versao);
intent.putExtra("tab", "0");
startActivity(intent);
}
});
}
else {
android.app.AlertDialog.Builder alerta = new android.app.AlertDialog.Builder(getActivity());
alerta.setMessage("Você está sem Acesso a Internet por favor verifique suas configurações, ative o wi-fi ou seus dados móveis");
alerta.setPositiveButton("OK", null);
alerta.show();
}
return tela;
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class Carregadados extends AsyncTask<String, Void, List<OSID>> {
private final ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPostExecute(List<OSID> result) {
super.onPostExecute(result);
dialog.dismiss();
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setCancelable(false);
dialog.setTitle("Carregando");
dialog.setMessage("Por Favor Aguarde");
dialog.show();
}
#Override
protected List<OSID> doInBackground(String... params) {
List<OSID> result = new ArrayList<OSID>();
ArrayList<NameValuePair> data = new ArrayList<>();
data.add(new BasicNameValuePair("id", String.valueOf(item.OSCodigo)));
HttpParams httprequestparams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httprequestparams, CONNECTION_TIME);
HttpConnectionParams.setSoTimeout(httprequestparams, CONNECTION_TIME) ;
HttpClient cliente = new DefaultHttpClient(httprequestparams);
HttpPost post = new HttpPost(SERVIDOR + "OS/CarregaVersaoOS");
try {
post.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = cliente.execute(post);
HttpEntity entity = response.getEntity();
String JSONResp = EntityUtils.toString(entity);
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(ConvertDados(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
public OSID ConvertDados(JSONObject obj) throws JSONException {
int oscodigo = obj.getInt("osCodigo");
int versao = obj.getInt("Versao");
String situacao = obj.getString("Situacao");
String finalidade = obj.getString("Finalidade");
String assunto = obj.getString("Assunto");
String previsao = obj.getString("PrevisaoAtendimento");
String solicitadopor = obj.getString("osSolicitadopor");
String solicitacao = obj.getString("Solicitacao");
solicitacao.replace("\r\n","Solicitação não preenchida");
String servico = obj.getString("ServicoExecutado");
String aberto = obj.getString("AbertoPor");
String executado = obj.getString("ExecutadoPor");
int versoes = 0;
return new OSID(oscodigo,versao,versoes,situacao,finalidade,assunto,previsao,solicitadopor,solicitacao,servico,aberto,executado);
}
}
Try this
#Override
public void onBackPressed() {
// call super.onBackPressed(); at last.
Intent intent = new Intent(OS.this, MainActivity.class);
intent.putExtra("position", 2);
startActivity(intent);
super.onBackPressed(); <----
}

Categories

Resources