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.
Related
I want change the background color of of LinearLayout of Fragment A from Fragment B .These fragments are in same viewpager in sliding tabs.
The data of both fragment are dynamically changed from server.Here I have to click a textview of Fragment B then its linearlayout's color be changed manually(POST method) but due to net slow the background color of Fragment A (Because the textview of Fragment A is already selected so its color is already set.) is not removed from LinearLayout(GET method). But after sometime it will disappear .
So I want to set color manually till color is to be loaded. To make good user interface while clicking on textview for selection package.
MinPackageFragment
public class MinPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private View mView;
private TextView nepal_minimum_package_price, nepal_minimum_package_plan;
private LinearLayout nepal_minimum_package_linearlayout;
private String GET_NEPAL_MIN_PACKAGE_URL;
private String CHECK_CURRENT_PACKAGE_URL;
private WebView webview;
private String minPackagePrice;
private String minPackageItem;
private int THIS_ID;
private String CHOOSE_PACKAGE;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_min_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1001;
GET_NEPAL_MIN_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1001?token=" + token;
webview = (WebView) mView.findViewById(R.id.minimumNepaliListWebView);
webview.getSettings().setJavaScriptEnabled(true);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_minimum_package_price = mView.findViewById(R.id.nepal_minimum_package_price);
nepal_minimum_package_plan = mView.findViewById(R.id.nepal_minimum_package_plan);
nepal_minimum_package_linearlayout = mView.findViewById(R.id.nepal_minimum_package_linearlayout);
nepal_minimum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I want change here the background color of linearlayout of another fragment but getting error
showDialog();
choosePackage();
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setContentFromServer();
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
String avgprice = pref123.getString("mineprice", minPackagePrice);
String avgitems = pref123.getString("minitems", minPackageItem);
nepal_minimum_package_price.setText(avgprice);
webview.loadData(avgitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return mView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
Log.v("mydata1", data + "");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
hideDialog();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setContentFromServer() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_MIN_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = silver.getString("name");
minPackagePrice = silver.getString("price");
minPackageItem = silver.getString("includes");
if (getActivity() != null) {
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref123.edit();
editor.putString("mineprice", minPackagePrice);
editor.putString("minitems", minPackageItem);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
MaxPackageFragment
public class MaxPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private WebView maximumNepaliListWebView;
private View maxView;
private TextView nepal_maximum_package_plan, nepal_maximum_package_price;
private String GET_NEPAL_PACKAGE_URL;
private String maxPackageprice;
private String maxPackageitems;
private String CHECK_CURRENT_PACKAGE_URL;
private LinearLayout nepal_maximum_package_linearlayout;
private String CHOOSE_PACKAGE;
private int THIS_ID;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
maxView = inflater.inflate(R.layout.fragment_max_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1003;
GET_NEPAL_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1003?token=" + token;
nepal_maximum_package_linearlayout = maxView.findViewById(R.id.nepal_maximum_package_linearlayout);
maximumNepaliListWebView = maxView.findViewById(R.id.maximumNepaliListWebView);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_maximum_package_plan = maxView.findViewById(R.id.nepal_maximum_package_plan);
nepal_maximum_package_price = maxView.findViewById(R.id.nepal_maximum_package_price);
nepal_maximum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
// I want change here the background color of linearlayout of another fragment but getting error
choosePackage();
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setItemToLayout();
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
String maxprice = pref1.getString("maxprice", maxPackageprice);
String maxitems = pref1.getString("maxitems", maxPackageitems);
nepal_maximum_package_price.setText(maxprice);
maximumNepaliListWebView.loadData(maxitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return maxView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1003) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
hideDialog();
}
}
}
else {
JSONArray errordata = responceData.getJSONArray("errors");
String errormessage = errordata.getJSONObject(0).getString("message");
Toast.makeText(getActivity(), "" + errormessage, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setItemToLayout() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
Log.v("responceData", "onResponse: " + responceData);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = platinum.getString("name");
maxPackageprice = platinum.getString("price");
maxPackageitems = platinum.getString("includes");
if (getActivity() != null) {
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("maxprice", maxPackageprice);
editor.putString("maxitems", maxPackageitems);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID ==1003){
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
There are three fragments in same viewpager of fragment,within three tabs.
If your fragment is in same Activity, You can use the FragmentManager. findFragmentById(int id) which return by invoke Fragment.getFragmentManager() method to retrieve the reference of another fragment
then invoke the method to change the background color
I have to upload a file and has three more parameters which is string.The file can be image or zip.How is it possible with volley to upload a file and submit string parameters along with it when button is clicked?
I have also tried this link-https://www.simplifiedcoding.net/upload-pdf-file-server-android/
Please help me.Thanks!!
My code is:
public class Tab1Fragment extends Fragment implements
AdapterView.OnItemSelectedListener {
EditText subj,desx;
private ImageView mAvatarImage;
Button choosefile,select,submt;
String uid, type;
String MY_PREFS_NAME = "value";
private int PICK_PDF_REQUEST = 1;
TextView filetext;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
String uploadId;
//Uri to store the image uri
private Uri filePath;
Spinner spinner,spinner2;
public Tab1Fragment() {
// Required empty public constructor
}
public static Tab1Fragment newInstance() {
Tab1Fragment fragment = new Tab1Fragment();
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_tab1, container,
false);
subj=(EditText)rootview.findViewById(R.id.subj);
choosefile=(Button)rootview.findViewById(R.id.choosefile);
select=(Button)rootview.findViewById(R.id.select);
submt=(Button)rootview.findViewById(R.id.submt);
filetext=(TextView)rootview.findViewById(R.id.filetext);
mAvatarImage=(ImageView)rootview.findViewById(R.id.image);
desx=(EditText)rootview.findViewById(R.id.desx);
submt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveProfileAccount();
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
choosefile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadMultipart();
}
});
requestStoragePermission();
SharedPreferences prefs =
this.getActivity().getSharedPreferences(MY_PREFS_NAME,
Context.MODE_PRIVATE);
uid = prefs.getString("uid", null);
spinner = (Spinner)rootview.findViewById(R.id.spinner);
spinner2 = (Spinner)rootview.findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> deparment= new ArrayList<String>();
deparment.add("Support");
deparment.add("Project");
deparment.add("Payment");
deparment.add("Service");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, deparment);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
List<String> priority= new ArrayList<String>();
priority.add("low");
priority.add("Medium");
priority.add("High");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, priority);
// Drop down layout style - list view with radio button
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner2.setAdapter(dataAdapter2);
return rootview;
}
private void saveProfileAccount() {
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.UPLOAD_SUPPORT, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject b = new JSONObject(resultResponse);
int status = b.getInt("status");
String data = b.getString("message");
Log.d("Response", data);
if (status ==100) {
/* Intent intent = new Intent(getActivity(),Skills.class);
startActivity(intent);*/
Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("userid", uid);
params.put("department", spinner.getSelectedItem().toString());
params.put("priority",
spinner2.getSelectedItem().toString().trim());
params.put("subject", subj.getText().toString().trim());
params.put("description",desx.getText().toString().trim());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getContext(), mAvatarImage.getDrawable()), "*/*"));
return params;
}
};
VolleySingleton.getInstance(getContext()).addToRequestQueue(multipartRequest);
}
try this
public void fileUploadFunction() {
// Getting file path using Filepath class.
Pdfuri = FilePath.getPath(this, uri);
Log.d("Pdfuri", Pdfuri);
// If file path object is null then showing toast message to move file into internal storage.
if (Pdfuri == null) {
Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show();
}
// If file path is not null then PDF uploading file process will starts.
else {
try {
PdfID = UUID.randomUUID().toString();
new MultipartUploadRequest(this, PdfID, AppConstants.URL)
.addFileToUpload(Pdfuri, "pdf")
.addParameter("course", course.trim())
.addParameter("course_id", c_id.trim())
.addParameter("stream", stream.trim())
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload();
Toast.makeText(MainActivity.this,"Successfully Uploaded",Toast.LENGTH_SHORT).show();
} catch (Exception exception) {
Toast.makeText(this,
exception.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
//Read response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Add post values here
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// Add you file here
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
You can use multipart for this. Here is a sample code
I am trying to implement Ranking for city, country and Worldwide in my App while fetching data using Volley as JSON response and loading it in seperate ArrayList. My problem is that it loads data in arrayList but pagerAdapter.notifyDataSetChanged() does not reflect the new data until you manual rotate mobile orientation and onCreate() or onResume() is called automatically. Bellow is the code for RatingActivity.java. and BlankFragment.java to load cards(Recyclers).
RatingActivity.java
public class RatingActivity extends AppCompatActivity {
String user,aun, aps;
int lst=0;
public static ArrayList<String> emailst1, ranklst1, namelst1, ratinglst1;
public static ArrayList<String> emailst2, ranklst2, namelst2, ratinglst2;
public static ArrayList<String> emailst3, ranklst3, namelst3, ratinglst3;
public static PagerAdapter pagerAdapter;
TextView txtmyrank, txtmyname, txtmyrating;
public static int ran[]={0,0,0};
public static int tabpost;
public String[] usdtl={"","","",""};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
javalib jl = new javalib();
txtmyrank=(TextView)findViewById(R.id.txtmyrank);
txtmyname=(TextView)findViewById(R.id.txtmyname);
txtmyrating=(TextView)findViewById(R.id.txtmyrating);
aun = jl.HelloJNI();
aps = jl.HiJNI();
aps=aps.substring(0,aps.length()-1);
DBHelper db = new DBHelper(this);
//Log.e("Called","yeh");
SessionM session = new SessionM(this);
// get user data from session
HashMap<String, String> user;
user = session.getUserDetails();
String Usremail = user.get(SessionM.KEY_EMAIL);
usdtl = db.getUserDetail(Usremail);
String loc = usdtl[1];
emailst1 = new ArrayList<String>();
ranklst1 = new ArrayList<String>();
namelst1 = new ArrayList<String>();
ratinglst1 = new ArrayList<String>();
emailst2 = new ArrayList<String>();
ranklst2 = new ArrayList<String>();
namelst2 = new ArrayList<String>();
ratinglst2 = new ArrayList<String>();
emailst3 = new ArrayList<String>();
ranklst3 = new ArrayList<String>();
namelst3 = new ArrayList<String>();
ratinglst3 = new ArrayList<String>();
String[] address={"",""};
address[0]=loc.substring(0,loc.indexOf(','));
address[1]=loc.substring(loc.indexOf(',')+1,loc.length());
txtmyname.setText(usdtl[2]);
txtmyrating.setText(usdtl[3]);
//////////////////////////// update rank///////////////////////////////////////////////////////////////
String url = "http://abcd.net/getRank.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location1="+address[0]+"&location2="+address[1]+"&app=0";
Log.e("Url", url);
RequestQueue requestQueue = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar4 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("rank");
if (isUpdate == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
Log.e("Rank response", response.toString());
ran[il]=Integer.parseInt(response.getJSONObject(il).getString("rank"));
il++;
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue.add(jar4);
url = "http://abcd.net/ctranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[0]+"&cpage=1&app=0";
requestQueue = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar1 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst1 = new ArrayList<String>();
namelst1 = new ArrayList<String>();
ratinglst1 = new ArrayList<String>();
while (il < lng) {
ranklst1.add((il+1)+"");
emailst1.add(response.getJSONObject(il).getString("username"));
namelst1.add(response.getJSONObject(il).getString("name"));
ratinglst1.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue.add(jar1);
url = "http://abcd.net/cntranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[1]+"&cpage=1&app=0";
RequestQueue requestQueue2 = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar2 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst2 = new ArrayList<String>();
namelst2 = new ArrayList<String>();
ratinglst2 = new ArrayList<String>();
while (il < lng) {
ranklst2.add((il+1)+"");
emailst2.add(response.getJSONObject(il).getString("username"));
namelst2.add(response.getJSONObject(il).getString("name"));
ratinglst2.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue2.add(jar2);
url = "http://abcd.net/wwranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&cpage=1&app=0";
RequestQueue requestQueue3 = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar3 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst3 = new ArrayList<String>();
namelst3 = new ArrayList<String>();
ratinglst3 = new ArrayList<String>();
while (il < lng) {
ranklst3.add((il+1)+"");
emailst3.add(response.getJSONObject(il).getString("username"));
namelst3.add(response.getJSONObject(il).getString("name"));
ratinglst3.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue3.add(jar3);
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
public void setList(){
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), RatingActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
switch(position){
case 0:
ran[0]=emailst1.indexOf(usdtl[0])+1;
break;
case 1:
ran[1]=emailst2.indexOf(usdtl[0])+1;
break;
case 2:
ran[2]=emailst3.indexOf(usdtl[0])+1;
break;
}
txtmyrank.setText(ran[position]+"");
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "શહેર", "દેશ", "વૈશ્વિક" };
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
Bundle extra = new Bundle();
switch (position) {
case 0:
tabpost=1;
break;
case 1:
tabpost=2;
break;
case 2:
tabpost=3;
break;
}
extra.putString("position", tabpost+"");
BlankFragment bf = new BlankFragment();
bf.setArguments(extra);
return bf;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(RatingActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
Following is the code for BlankFragment.java
public class BlankFragment extends Fragment {
int tabpost;
Boolean userScrolled=false;
ArrayList<String> alstname, alstrank, alstrating;
public BlankFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tabpost=Integer.parseInt(getArguments().getString("position"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
final RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
switch (tabpost) {
case 1:
alstname = RatingActivity.namelst1;
alstrank = RatingActivity.ranklst1;
alstrating = RatingActivity.ratinglst1;
break;
case 2:
alstname = RatingActivity.namelst2;
alstrank = RatingActivity.ranklst2;
alstrating = RatingActivity.ratinglst2;
break;
case 3:
alstname = RatingActivity.namelst3;
alstrank = RatingActivity.ranklst3;
alstrating = RatingActivity.ratinglst3;
break;
}
MyAdapter adapter = new MyAdapter(alstname, alstrank, alstrating);
rv.setAdapter(adapter);
final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.e("dx, dy", dx+" "+dy);
int visibleItemCount = llm.getChildCount();
int totalItemCount = llm.getItemCount();
int pastVisiblesItems = llm.findFirstVisibleItemPosition();
if (userScrolled
&& (visibleItemCount + pastVisiblesItems) == totalItemCount) {
userScrolled = false;
///////////////// updating rank list////////////////////////////////////
switch (tabpost) {
case 1:
Log.e("Updating","Recycler View1"+tabpost);
updatelist(1, totalItemCount);
break;
case 2:
Log.e("Updating","Recycler View2"+tabpost);
updatelist(2, totalItemCount);
break;
case 3:
Log.e("Updating","Recycler View3"+tabpost);
updatelist(3, totalItemCount);
break;
}
/////////////////////////////////////////////////////////////////////////
}
}
});
rv.setLayoutManager(llm);
return rootView;
}
void updatelist(int post, int item){
javalib jl = new javalib();
String aun = jl.HelloJNI();
String aps = jl.HiJNI();
aps=aps.substring(0,aps.length()-1);
DBHelper db = new DBHelper(getContext());
//Log.e("Called","yeh");
SessionM session = new SessionM(getContext());
// get user data from session
HashMap<String, String> user;
user = session.getUserDetails();
String Usremail = user.get(SessionM.KEY_EMAIL);
String[] usdtl = db.getUserDetail(Usremail);
String loc = usdtl[1];
String[] address={"",""};
address[0]=loc.substring(0,loc.indexOf(','));
address[1]=loc.substring(loc.indexOf(',')+1,loc.length());
int page1;
if(item==0)
page1=1;
else
page1=(item-1)/3 + 2;
String url = "http://abcd.net/ctranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[0]+"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jar1 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
RatingActivity.ranklst1.add((RatingActivity.ranklst1.size()+1)+"");
RatingActivity.emailst1.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst1.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst1.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
url = "http://abcd.net/cntranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[1]+"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue2 = Volley.newRequestQueue(getContext());
JsonArrayRequest jar2 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
/*RatingActivity.ranklst2 = new ArrayList<String>();
RatingActivity.namelst2 = new ArrayList<String>();
RatingActivity.ratinglst2 = new ArrayList<String>();*/
while (il < lng) {
RatingActivity.ranklst2.add((RatingActivity.ranklst2.size()+1)+"");
RatingActivity.emailst2.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst2.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst2.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
url = "http://abcd.net/wwranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue3 = Volley.newRequestQueue(getContext());
JsonArrayRequest jar3 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
RatingActivity.ranklst3.add((RatingActivity.ranklst3.size()+1)+"");
RatingActivity.emailst3.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst3.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst3.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
switch (post) {
case 1: requestQueue.add(jar1);
break;
// Adding request to request queue
case 2:
requestQueue2.add(jar2);
break;
// Adding request to request queue
case 3: requestQueue3.add(jar3);
break;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
Here is my code, I have to call method getServerResponse() for first time to get store in arraylist and when I scrolls down I have to call method getServerResponseScroll(). I got result and notify adapter but after scrolling down and up data changes position or may be not visible or get changed. I had created custom adapter for chat. Please help me how to sort out this kind of problem.
public class ChatDetailActivity extends AppCompatActivity {
String macAddress;
RecyclerView recyclerView;
Activity context;
ChatAdapter adapter;
EditText etText;
DatabaseAdapter db;
NetClient nc;
EditText edtSend;
Button btnSend;
DataPref mDataPref;
static int page = 0;
SwipeRefreshLayout mSwipeRefreshLayout;
JSONArray chatDetailListJsonArray;
String toId, channelId, toProfilePic, deviceToken, deviceOsType;
static ArrayList<ChatDetailModel> chatDetailModels = new ArrayList<ChatDetailModel>();
// User mchatUSer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_detail);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
edtSend = (EditText) findViewById(R.id.edtSend);
btnSend = (Button) findViewById(R.id.btnSend);
db = new DatabaseAdapter(this);
mDataPref = DataPref.getInstance(this);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
macAddress = wInfo.getMacAddress();
etText = (EditText) findViewById(R.id.etText);
toId = getIntent().getStringExtra("toId");
channelId = getIntent().getStringExtra("channelId");
toProfilePic = getIntent().getStringExtra("toProfilePic");
deviceToken = getIntent().getStringExtra("deviceToken");
deviceOsType = getIntent().getStringExtra("deviceOsType");
getServerResponse(this);
connectionForSend();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
void getServerResponse(final Context context){
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
/*
if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
if(page==0) {
GetChat.getInstance(context).deleteAllTableData("tbl_chat_detail", channelId);
}
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
} catch (JSONException e) {
e.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
// DatabaseAdapter.deleteDatabase(context);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page",page+"");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void getServerResponseScroll(final Context context) {
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
// chatDetailModels.clear();
ArrayList<ChatDetailModel> chatDetailModels1 = new ArrayList<ChatDetailModel>();
chatDetailModels1 = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
chatDetailModels.clear();
chatDetailModels.addAll(chatDetailModels1);
mSwipeRefreshLayout.setRefreshing(false);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
// DatabaseAdapter.deleteDatabase(context);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page", page + "");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void implemantation() {
RecyclerView.LayoutManager manager = new LinearLayoutManager(this.getApplicationContext());
recyclerView.setLayoutManager(manager);
adapter = new ChatAdapter(this.getApplicationContext(), chatDetailModels);
recyclerView.setAdapter(adapter);
recyclerView.scrollToPosition(chatDetailModels.size() - 1);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(ChatDetailActivity.this, ProfilesDetailActivity.class);
// i.putExtra("profileId",ChatlistModel.get(position).getId());
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
}));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
page++;
getServerResponseScroll(ChatDetailActivity.this);
}
});
}
// Adapter for chat
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
private ArrayList<ChatDetailModel> chatDetailModels;
private Context context;
public ChatAdapter(Context context, ArrayList<ChatDetailModel> chatDetailModels) {
this.context = context;
this.chatDetailModels = chatDetailModels;
}
#Override
public ChatAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_lsit_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
if (chatDetailModels.get(position).getFrom_username().equalsIgnoreCase(mDataPref.getUsername())) {
viewHolder.messageTextRight.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatLeftLayout.setVisibility(View.GONE);
if (mDataPref.getProfilePicFullUrl().equals("null") || mDataPref.getProfilePicFullUrl().equals("")) {
viewHolder.fromImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(mDataPref.getProfilePicFullUrl()).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.fromImageView);
}
} else {
viewHolder.messageTextLeft.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatRightLayout.setVisibility(View.GONE);
if (toProfilePic.equals("null") || toProfilePic.equals("")) {
viewHolder.toImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(toProfilePic).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.toImageView);
}
}
}
#Override
public int getItemCount() {
return chatDetailModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout chatLeftLayout;
private ImageView toImageView;
private TextView messageTextLeft;
private LinearLayout chatRightLayout;
private TextView messageTextRight;
private ImageView fromImageView;
public ViewHolder(View view) {
super(view);
chatLeftLayout = (LinearLayout) view.findViewById(R.id.chatLeftLayout);
toImageView = (ImageView) view.findViewById(R.id.toImageView);
messageTextLeft = (TextView) view.findViewById(R.id.message_text_left);
chatRightLayout = (LinearLayout) view.findViewById(R.id.chatRightLayout);
messageTextRight = (TextView) view.findViewById(R.id.message_text_right);
fromImageView = (ImageView) view.findViewById(R.id.fromImageView);
}
}
}
}
From onSaveInstanceState documentation:
Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.
* RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.
To get current state of recyclerview:
private Parcelable recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
to restore saved instance:
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
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();
}
}