ViewPager have stuck while Swiping - android

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")

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);
}
}

Return button to previous activity with BaseAdapter

I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}

Swipe Refresh layout

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();
}
}

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(); <----
}

Why OnItemClickLIstener Is Not Work for PullToRefreshLIstView?

I am Using following code:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
setAllControlls();
myPrefs = this.getSharedPreferences(
AppConstants.MYPREF, MODE_WORLD_READABLE);
userid = myPrefs.getString(AppConstants.USER_ID, "");
if(checkInternet(NewFeeds.this))
{
new callNewsfeeddata().execute(userid);
}
else
{
Toast.makeText(NewFeeds.this,"Please Check Your Internet Connection",Toast.LENGTH_LONG).show();
}
objlistview.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
if(checkInternet(NewFeeds.this))
{
new callNewsfeeddata().execute(userid);
}
else
{
Toast.makeText(NewFeeds.this,"Please Check Your Internet Connection",Toast.LENGTH_LONG).show();
}
}
});
objHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case AppConstants.UPDATE_ADDRESS:
if (!((String) msg.obj).equals("0")) {
System.out.println("inside---" + objlocationvalue);
objlocationvalue = (String) msg.obj;
} else {
objlocationvalue = "1";
}
break;
}
}
};
objLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
private void setAllControlls() {
objlistview = (PullToRefreshListView) findViewById(R.id.newsfeedlistview);
objlistview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
int pos1=pos-1;
NewsFeedModle objnewsfeedmodle = objlist.get(pos);
String type = objnewsfeedmodle.getType();
if(type.equalsIgnoreCase("job"))
{
String postid = objnewsfeedmodle.getJobId();
Intent objintent = new Intent(NewFeeds.this,ShowNewPostJobDetails.class);
Bundle objbundle = new Bundle();
objbundle.putString("postid", postid);
objbundle.putString("from","newsfeed");
objintent.putExtras(objbundle);
startActivity(objintent);
}
if(type.equalsIgnoreCase("deals"))
{
String postid = objnewsfeedmodle.getDealid();
Intent objintent = new Intent(NewFeeds.this,ShowNewFindDeal.class);
Bundle objbundle = new Bundle();
objbundle.putString("postid", postid);
objbundle.putString("from","newsfeed");
objintent.putExtras(objbundle);
startActivity(objintent);
}
if(type.equalsIgnoreCase("stuff"))
{
String postid = objnewsfeedmodle.getStuffId();
Intent objintent = new Intent(NewFeeds.this,ShowNewFindStuff.class);
Bundle objbundle = new Bundle();
objbundle.putString("postid", postid);
objbundle.putString("from","newsfeed");
objintent.putExtras(objbundle);
startActivity(objintent);
}
}
});
}
private class callNewsfeeddata extends
AsyncTask<String, Void, List<NewsFeedModle>> {
ProgressDialog objprogress = new ProgressDialog(NewFeeds.this);
AppRequestHandler objApprequest = new AppRequestHandler();
List<NewsFeedModle> objresponce = new ArrayList<NewsFeedModle>();
#Override
protected void onPreExecute() {
objprogress.setMessage("Please Wait While Loading...");
objprogress.show();
}
#Override
protected List<NewsFeedModle> doInBackground(String... params) {
objresponce = objApprequest.newsFeedRequest(params[0]);
return objresponce;
}
#Override
protected void onPostExecute(List<NewsFeedModle> result) {
if (objprogress.isShowing()) {
objprogress.dismiss();
}
if(objlist!=null && objlist.size()!=0)
{
objlist.clear();
}
String msgcount="";
if (result != null)
{
objlist=result;
if(objlist.size()==0)
{
Log.i("check",""+objlist.size());
Log.i("check22222",""+result.size());
}
if(objlist!=null && objlist.size()!=0)
{
msgcount = objlist.get(0).getMessagescount();
}
TabActivity tab=(TabActivity) getParent();
TextView tv=(TextView) tab.findViewById(R.id.notificationmsg);
tv.setText(msgcount);
Editor objedit = myPrefs.edit();
objedit.putString(AppConstants.MESSAGECOUNT, msgcount);
objedit.commit();
objnewsFeedAdapter = new NewsFeedAdapter(NewFeeds.this,objlist,(float)objlattvalue,(float)objlongvalue,objlocationvalue);
objlistview.setAdapter(objnewsFeedAdapter);
objnewsFeedAdapter.notifyDataSetChanged();
objlistview.onRefreshComplete();
}
}
}
I have define OnItemClickLIstener inside setAllContrill method but it is not working.listView is unclickable anyone suggest me .I am using github pulltorefresh code .I unable to find out what is issue because in other places it is working..
Try: `
objlistview.getRefreshableView().setOnItemClickListener(new OnItemClickListener...)
getRefreshableView() won't help, because setOnItemClickListener() in PullToRefreshListView is just a pass-through method:
public void setOnItemClickListener(OnItemClickListener listener) {
mRefreshableView.setOnItemClickListener(listener);
}
I had the same problem, and it turned out that I had clickable element in item layout. After making this element non-clickable it began to work.

Categories

Resources