performItemClick on item in Android Navigation Drawer not working - android

I have a sliding drawer, and in the drawer is a ListView with 4 items. I would like to use performItemClick to programmatically click one of the items in the drawer, but no matter what I try the code seemingly does nothing. When the item is clicked it's supposed to replace the fragment currently in view with another fragment, and change the action bar title. But none of those things happen with I run performItemClick.
Here is the performItemClick, in a BroadcastReceiver which is receiving a Broadcast
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mDrawerList.performItemClick(mDrawerList.getAdapter().getView(1, null, null),1,mDrawerList.getAdapter().getItemId(1));
Log.d("receiver", "Got message + item clicked");
}
};
And here is the code for the actual activity which contains the performItemClick and the drawer itself, along with the drawers fragments (the performItemClick is near the bottom).
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.view.GravityCompat;
import android.text.Html;
#SuppressLint("ResourceAsColor")
public class MainActivity extends SherlockFragmentActivity {
private String Data, Band, Number, Class, Teacher, Title, Date, Type, Description, DescriptionAll, DescriptionCheck;
// Declare Variables
DrawerLayout mDrawerLayout;
LinearLayout mDrawerLinear;
TextView mWelcomePerson;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String actionbar_colors, background_colorsString;
private String Show_View;
String[] title;
String[] count;
int[] icon;
private String counterss;
private int counters;
Fragment fragment1 = new FragmentsView();
Fragment fragment2 = new FragmentsHomeworkDue();
Fragment fragment3 = new FragmentSettings();
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedprefers = getSharedPreferences("first_run", Context.MODE_PRIVATE );
if(sharedprefers.contains("first_run")){
}else{
SharedPreferences.Editor localEditor = getSharedPreferences("first_run", Context.MODE_PRIVATE ).edit();
localEditor.putString("first_run", "ran for the first time");
localEditor.commit();
Intent intenter = new Intent(this, MainActivity.class);
finish();
startActivity(intenter);
}
setContentView(R.layout.drawer_main);
SharedPreferences sharedpre = getSharedPreferences("show_view", Context.MODE_PRIVATE );
Show_View = sharedpre.getString("show_view", "");
SharedPreferences sharedpref = getSharedPreferences("actionbar_color", Context.MODE_PRIVATE );
if(!sharedpref.contains("actionbar_color")){
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#03a9f4")));
}else{
actionbar_colors = sharedpref.getString("actionbar_color", null);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(actionbar_colors)));
}
ActionBar bar = getSupportActionBar();
bar.setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
mTitle = mDrawerTitle = getTitle();
SharedPreferences Today_Homework = getApplicationContext().getSharedPreferences("due_today", Context.MODE_PRIVATE);
if(Today_Homework.contains("duetoday_content")){
parse_due_today_string();
}else{
counterss = "";
}
if(Show_View.equals("Homework Due")){
title = new String[] { "Homework Due", "Schedule", "Options", "Logout" };
icon = new int[] { R.drawable.ic_action_duehomework, R.drawable.ic_action_go_to_today, R.drawable.ic_action_settings, R.drawable.ic_action_logout };
if(counterss == null && counterss.isEmpty()){
count = new String[] { "", "", "", "" };
}
else{
count = new String[] { counterss, "", "", "" };
}
}else{
if(counterss == null && counterss.isEmpty()){
count = new String[] { "", "", "", "" };
}else{
count = new String[] { "", counterss, "", "" };
}
title = new String[] { "Schedule", "Homework Due", "Options", "Logout" };
icon = new int[] { R.drawable.ic_action_go_to_today, R.drawable.ic_action_duehomework, R.drawable.ic_action_settings, R.drawable.ic_action_logout };
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLinear = (LinearLayout) findViewById(R.id.left_drawer);
mWelcomePerson = (TextView) findViewById(R.id.Person);
mWelcomePerson.setText("Lincoln Bernard");
mDrawerList = (ListView) findViewById(R.id.listview_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mMenuAdapter = new MenuListAdapter(MainActivity.this, title,
icon, count);
mDrawerList.setAdapter(mMenuAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
getSupportActionBar().setTitle(mDrawerTitle);
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("up_navigation"));
}
public void parse_due_today_string() {
SharedPreferences Today_Homework = getApplicationContext().getSharedPreferences("due_today", Context.MODE_PRIVATE);
String Due_Today = Today_Homework.getString("duetoday_content", "");
ArrayList<String> description = new ArrayList<String>( );
StringBuilder DescriptionAll = new StringBuilder();
InputStream is = new ByteArrayInputStream(Due_Today.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
int i = 0;
while ((Due_Today = reader.readLine()) != null) {
String[] part = Due_Today.split("\",\"", -1);
int noOfItems = part.length;
int counter=0;
DescriptionCheck = counter<noOfItems ? part[counter] : "";
counter++;
Band = counter<noOfItems ? part[counter] : "";
counter++;
Number = counter<noOfItems ? part[counter] : "";
counter++;
Class = counter<noOfItems ? part[counter] : "";
counter++;
Teacher = counter<noOfItems ? part[counter] : "";
counter++;
Title = counter<noOfItems ? part[counter] : "";
counter++;
Date = counter<noOfItems ? part[counter] : "";
counter++;
Type = counter<noOfItems ? part[counter] : "";
counter++;
Data = counter<noOfItems ? part[counter] : "";
counter++;
if (Type != null && !Type.isEmpty()){
counters = ++i;
counterss = Integer.toString(counters);
Log.i("Counter","Number of children: "+ counters);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerLinear)) {
mDrawerLayout.closeDrawer(mDrawerLinear);
} else {
mDrawerLayout.openDrawer(mDrawerLinear);
}
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(Show_View.equals("Homework Due")){
switch (position) {
case 0:
ft.replace(R.id.content_frame,fragment2);
break;
case 1:
ft.replace(R.id.content_frame, fragment1);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
}
}else{
switch (position) {
case 0:
ft.replace(R.id.content_frame,fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
}
}
ft.commit();
mDrawerList.setItemChecked(position, true);
/
setTitle(title[position]);
mDrawerLayout.closeDrawer(mDrawerLinear);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("receiver", "Got");
mDrawerList.performItemClick(mDrawerList.getAdapter().getView(1, null, null),1,mDrawerList.getAdapter().getItemId(1));
Log.d("receiver", "Got message");
}
};
#Override
public void onBackPressed() {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
manager.popBackStack();
} else {
super.onBackPressed();
}
}
}
MenuListAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MenuListAdapter extends BaseAdapter {
Context context;
String[] mTitle;
String[] mCount;
int[] mIcon;
LayoutInflater inflater;
public MenuListAdapter(Context context, String[] title,
int[] icon, String[] count) {
this.context = context;
this.mTitle = title;
this.mIcon = icon;
this.mCount = count;
}
#Override
public int getCount() {
return mTitle.length;
}
#Override
public Object getItem(int position) {
return mTitle[position];
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView txtTitle;
ImageView imgIcon;
TextView txtCount;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.drawer_list_item, parent,
false);
txtTitle = (TextView) itemView.findViewById(R.id.title);
txtCount = (TextView) itemView.findViewById(R.id.counter);
imgIcon = (ImageView) itemView.findViewById(R.id.icon);
txtTitle.setText(mTitle[position]);
txtCount.setText(mCount[position]);
imgIcon.setImageResource(mIcon[position]);
return itemView;
}
}

What I have done is something like this inside my Expandable listview adapter for Drawer..
View.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
switch (groupPosition)
{
case 0:
switch (childPosition)
{
case 0:
if (groupPosition == 0 && childPosition == 0)
{ some code }
Edit: this switch starts different activity (or change view if fragment) on each respective item click.. in your case their will be fragments..

Related

Connection timed out android studio android pie version 9

I created android application grocery app using android studio. when i open some devices it showing connection timed out keep on loading. but some other devices working. please check attached screenshot. please tell me which code i need to check
Thank you
Note : Especially Android 9 Pie Mobile devices getting this error
Mainactivity.java
package woodland.bharati;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.webkit.WebView;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.telephony.PhoneNumberUtils;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SubMenu;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import Config.BaseURL;
import Config.SharedPref;
import Fonts.CustomTypefaceSpan;
import Fragment.About_us_fragment;
import Fragment.Contact_Us_fragment;
import Fragment.Empty_cart_fragment;
import Fragment.Home_fragment;
import Fragment.Cart_fragment;
import Fragment.Reward_fragment;
import Fragment.Edit_profile_fragment;
import Fragment.Shop_Now_fragment;
import Fragment.Terms_and_Condition_fragment;
import Fragment.Wallet_fragment;
import woodland.bharati.networkconnectivity.NetworkError;
import util.ConnectivityReceiver;
import util.DatabaseHandler;
import util.Session_management;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, ConnectivityReceiver.ConnectivityReceiverListener {
private static final String TAG = MainActivity.class.getSimpleName();
private BroadcastReceiver mRegistrationBroadcastReceiver;
private TextView totalBudgetCount, totalBudgetCount2, totalBudgetCount3, tv_name, powerd_text;
private ImageView iv_profile;
private DatabaseHandler dbcart;
private Session_management sessionManagement;
private Menu nav_menu;
ImageView imageView;
TextView mTitle;
LinearLayout viewpa;
Toolbar toolbar;
String language="";
LinearLayout My_Order, My_Reward, My_Walllet, My_Cart;
int padding = 0;
private TextView txtRegId;
NavigationView navigationView;
LinearLayout Change_Store;
String Store_Count;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void attachBaseContext(Context newBase) {
newBase = LocaleHelper.onAttach(newBase);
super.attachBaseContext(newBase);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("MYTAG", "This is your Firebase token" + token);
sharedPreferences= getSharedPreferences("lan", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString("language", "english");
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("MainActivity") && value.equals("True")) {
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
subscribeToPushService();
}
Store_Count = SharedPref.getString(MainActivity.this, BaseURL.KEY_STORE_COUNT);
//
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setPadding(padding, toolbar.getPaddingTop(), padding, toolbar.getPaddingBottom());
setSupportActionBar(toolbar);
for (int i = 0; i < toolbar.getChildCount(); i++) {
View view = toolbar.getChildAt(i);
if (view instanceof TextView) {
TextView textView = (TextView) view;
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "Font/Bold.ttf");
textView.setTypeface(myCustomFont);
}
}
getSupportActionBar().setTitle(getResources().getString(R.string.name));
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
dbcart = new DatabaseHandler(this);
checkConnection();
sessionManagement = new Session_management(MainActivity.this);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu m = navigationView.getMenu();
for (int i = 0; i < m.size(); i++) {
MenuItem mi = m.getItem(i);
//for aapplying a font to subMenu ...
SubMenu subMenu = mi.getSubMenu();
if (subMenu != null && subMenu.size() > 0) {
for (int j = 0; j < subMenu.size(); j++) {
MenuItem subMenuItem = subMenu.getItem(j);
applyFontToMenuItem(subMenuItem);
}
}
//the method we have create in activity
applyFontToMenuItem(mi);
}
View headerView = navigationView.getHeaderView(0);
navigationView.getBackground().setColorFilter(0x80000000, PorterDuff.Mode.MULTIPLY);
navigationView.setNavigationItemSelectedListener(this);
nav_menu = navigationView.getMenu();
View header = ((NavigationView) findViewById(R.id.nav_view)).getHeaderView(0);
Change_Store = (LinearLayout) header.findViewById(R.id.change_store_btn);
viewpa=(LinearLayout) header.findViewById(R.id.viewpa);
if (sessionManagement.isLoggedIn()) {
viewpa.setVisibility(View.VISIBLE);
}
if (Store_Count.equals("1")) {
Change_Store.setVisibility(View.INVISIBLE);
} else if (Store_Count.equals("2")) {
Change_Store.setVisibility(View.VISIBLE);
Change_Store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SelectStore.class);
startActivity(intent);
overridePendingTransition(0, 0);
}
});
}
iv_profile = (ImageView) header.findViewById(R.id.iv_header_img);
tv_name = (TextView) header.findViewById(R.id.tv_header_name);
My_Order = (LinearLayout) header.findViewById(R.id.my_orders);
My_Reward = (LinearLayout) header.findViewById(R.id.my_reward);
My_Walllet = (LinearLayout) header.findViewById(R.id.my_wallet);
My_Cart = (LinearLayout) header.findViewById(R.id.my_cart);
My_Order.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, My_Order_activity.class);
startActivity(intent);
}
});
My_Reward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fm = new Reward_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
});
My_Walllet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fm = new Wallet_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
});
My_Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (dbcart.getCartCount() > 0) {
Fragment fm = new Cart_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
} else {
Toast.makeText(MainActivity.this, "No Item in Cart", Toast.LENGTH_SHORT).show();
}
}
});
iv_profile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
if (sessionManagement.isLoggedIn()) {
Fragment fm = new Edit_profile_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
} else {
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
overridePendingTransition(0, 0);
}
}
});
updateHeader();
sideMenu();
if (savedInstanceState == null) {
Fragment fm = new Home_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.contentPanel, fm, "Home_fragment")
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
getFragmentManager().
addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
try {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
Fragment fr = getFragmentManager().findFragmentById(R.id.contentPanel);
final String fm_name = fr.getClass().getSimpleName();
Log.e("backstack: ", ": " + fm_name);
if (fm_name.contentEquals("Home_fragment")) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
toggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
} else if (fm_name.contentEquals("My_order_fragment") ||
fm_name.contentEquals("Thanks_fragment")) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.syncState();
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fm = new Home_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
});
} else {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.syncState();
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
// if (sessionManagement.getUserDetails().
// get(BaseURL.KEY_ID) != null && !sessionManagement.getUserDetails().
// get(BaseURL.KEY_ID).equalsIgnoreCase())
//
// {
// MyFirebaseRegister fireReg = new MyFirebaseRegister(this);
// fireReg.RegisterUser(sessionManagement.getUserDetails().get(BaseURL.KEY_ID));
// }
}
public void updateHeader() {
if (sessionManagement.isLoggedIn()) {
String getname = sessionManagement.getUserDetails().get(BaseURL.KEY_NAME);
String getimage = sessionManagement.getUserDetails().get(BaseURL.KEY_IMAGE);
String getemail = sessionManagement.getUserDetails().get(BaseURL.KEY_EMAIL);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");
if (!previouslyEncodedImage.equalsIgnoreCase("")) {
byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
iv_profile.setImageBitmap(bitmap);
}
// Glide.with(this)
// .load(BaseURL.IMG_PROFILE_URL + getimage)
// .placeholder(R.drawable.icon)
// .crossFade()
// .into(iv_profile);
tv_name.setText(getname);
}
}
private void applyFontToMenuItem(MenuItem mi) {
Typeface font = Typeface.createFromAsset(getAssets(), "Font/Bold.ttf");
SpannableString mNewTitle = new SpannableString(mi.getTitle());
mNewTitle.setSpan(new CustomTypefaceSpan("", font), 0, mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mi.setTitle(mNewTitle);
}
public void sideMenu() {
if (sessionManagement.isLoggedIn()) {
// tv_number.setVisibility(View.VISIBLE);
nav_menu.findItem(R.id.nav_logout).setVisible(true);
nav_menu.findItem(R.id.nav_powerd).setVisible(true);
// nav_menu.findItem(R.id.nav_user).setVisible(true);
} else {
//tv_number.setVisibility(View.GONE);
tv_name.setText(getResources().getString(R.string.btn_login));
tv_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
}
});
nav_menu.findItem(R.id.nav_logout).setVisible(false);
// nav_menu.findItem(R.id.nav_user).setVisible(false);
}
}
public void setFinish() {
finish();
}
public void setCartCounter(String totalitem) {
try {
totalBudgetCount.setText(totalitem);
}catch (Exception e){
}
}
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_cart);
item.setVisible(true);
View count = item.getActionView();
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
menu.performIdentifierAction(item.getItemId(), 0);
}
});
totalBudgetCount = (TextView) count.findViewById(R.id.actionbar_notifcation_textview);
totalBudgetCount.setText("" + dbcart.getCartCount());
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.action_language){
openLanguageDialog();
}
if (id == R.id.action_cart) {
if (dbcart.getCartCount() > 0) {
Fragment fm = new Cart_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
else {
Fragment fm = new Empty_cart_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void openLanguageDialog() {
View v = LayoutInflater.from(this).inflate(R.layout.dialog_language,null,false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(v);
TextView lEnglish = v.findViewById(R.id.l_english);
TextView lSpanish = v.findViewById(R.id.l_arabic);
final AlertDialog dialog = builder.create();
lEnglish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LocaleHelper.setLocale(getApplication(),"en");
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
editor.putString("language", "english");
editor.apply();
recreate();
dialog.dismiss();
}
});
lSpanish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LocaleHelper.setLocale(getApplication(),"ar");
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("language", "spanish");
editor.apply();
recreate();
dialog.dismiss();
}
});
dialog.show();
}
#SuppressLint("ResourceType")
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fm = null;
Bundle args = new Bundle();
if (id == R.id.nav_shop_now) {
fm = new Shop_Now_fragment();
} else if (id == R.id.nav_my_profile) {
fm = new Edit_profile_fragment();
} else if (id == R.id.nav_support) {
String smsNumber = "919886143091";
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.Conversation"));
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber)+"#s.whatsapp.net");//phone number without "+" prefix
startActivity(sendIntent);
} else if (id == R.id.nav_aboutus) {
toolbar.setTitle("About");
fm = new About_us_fragment();
args.putString("url", BaseURL.GET_ABOUT_URL);
args.putString("title", getResources().getString(R.string.nav_about));
fm.setArguments(args);
}
else if (id == R.id.nav_youtube) {
toolbar.setTitle("Videos");
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://woodlandbharati.com/videos/"));
startActivity(myWebLink);
}
else if (id == R.id.nav_enquiry) {
toolbar.setTitle("Enquiry Us");
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://woodlandbharati.com/enquiry/"));
startActivity(myWebLink);
}
else if (id == R.id.nav_health) {
toolbar.setTitle("Health Tips");
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://woodlandbharati.com/news/"));
startActivity(myWebLink);
} else if (id == R.id.nav_policy) {
fm = new Terms_and_Condition_fragment();
args.putString("url", BaseURL.GET_TERMS_URL);
args.putString("title", getResources().getString(R.string.nav_terms));
fm.setArguments(args);
} else if (id == R.id.nav_review) {
//reviewOnApp();
} else if (id == R.id.nav_contact) {
fm = new Contact_Us_fragment();
args.putString("url", BaseURL.GET_SUPPORT_URL);
args.putString("title", getResources().getString(R.string.nav_terms));
fm.setArguments(args);
} else if (id == R.id.nav_share) {
shareApp();
} else if (id == R.id.nav_logout) {
sessionManagement.logoutSession();
finish();
} else if (id == R.id.nav_powerd) {
// stripUnderlines(textView);
String url = "http://bhavyabharath.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
finish();
}
if (fm != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void startActivityForResult(Intent intent, int requestCode) {
try {
super.startActivityForResult(intent, requestCode);
} catch (Exception ignored) {
}
}

Json don't update result in the seconde time

I have an activity where I can do a search through URL json file, so the 3 parameters pass from EditText of MainActivity to the second activity (annonces), the URL Json recovers the three values ​​and the results is normally displayed , but the problem if I made a return to MainActivity and I change the value of EditTexts and I click search, the results do not change.
this is my project :
MainActivity.java
package com.example.dzweber.waslup;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
AutoCompleteTextView cat;
String[] categories={"informatique","infographie","mathématique","Génie civil","Biologie"};
#Override
protected void onCreate(Bundle savedInstanceState) {
if(annonces.instance != null) {
annonces.instance.finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cat=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView2);
ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1,categories);
cat.setAdapter(adapter);
cat.setThreshold(1);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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 onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home) {
}
else if (id == R.id.login) {
Intent i = new Intent(this,login.class);
startActivity(i);
}
else if (id == R.id.avanced_search) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}
else if (id == R.id.annonces) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void as(View view) {
EditText loc;
EditText key;
loc = (EditText)findViewById(R.id.a_loc);
key = (EditText)findViewById(R.id.a_keys);
Intent intent = new Intent(getBaseContext(), annonces.class);
intent.putExtra("ca", cat.getText().toString());
intent.putExtra("lo",loc.getText().toString());
intent.putExtra("ke", key.getText().toString());
startActivity(intent);
}
public void connect(View view) {
}
}
annonces.java
package com.example.dzweber.waslup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.androidquery.AQuery;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONObject;
public class annonces extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static ArrayList<annonce_item> Items = new ArrayList<annonce_item>();
public static TextView txtv;
public static String data = "";
String skey = "";
String sloc = "";
String scat = "";
String date="";
String loc="";
String cat="";
String vue="";
String titre="";
String id="";
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public static annonces instance = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fetchD p = new fetchD();
//p.execute();
instance = this;
skey= getIntent().getStringExtra("ke");
sloc= getIntent().getStringExtra("lo");
scat= getIntent().getStringExtra("ca");
setContentView(R.layout.activity_annonces);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new AsyncCaller().execute();
TextView t = (TextView) findViewById(R.id.testing);
t.setText(scat);
// String generate = "https://www.waslup.pw/generation-json";
// String myurl = "https://www.waslup.pw/wp-content/uploads/wpdata.json";
// new MyAsyncTaskgetNews().execute(generate);
// new MyAsyncTaskgetNews().execute(myurl);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void finish() {
super.finish();
instance = null;
}
public void buclick(View view) {
}
#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) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.annonces, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home) {
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
finish();
}
else if (id == R.id.login) {
Intent i = new Intent(this,login.class);
startActivity(i);
}
else if (id == R.id.avanced_search) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}
else if (id == R.id.annonces) {
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class MyCustomAdapter extends BaseAdapter {
ArrayList<annonce_item> Items = new ArrayList<annonce_item>();
MyCustomAdapter(ArrayList<annonce_item> Items) {
this.Items = Items;
}
#Override
public int getCount() {
return Items.size();
}
#Override
public String getItem(int position) {
return Items.get(position).ititre;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater linflater = getLayoutInflater();
View view1 = linflater.inflate(R.layout.activity_annonce_item, null);
TextView id1 = (TextView) view1.findViewById(R.id.id);
TextView date1 = (TextView) view1.findViewById(R.id.date);
TextView cat1 = (TextView) view1.findViewById(R.id.cat);
TextView loc1 = (TextView) view1.findViewById(R.id.loc);
TextView titre1 = (TextView) view1.findViewById(R.id.titre);
TextView vue1 = (TextView) view1.findViewById(R.id.vue);
date1.setText(Items.get(i).idate);
id1.setText(Items.get(i).iid);
cat1.setText(Items.get(i).icat);
loc1.setText(Items.get(i).iloc);
titre1.setText(Items.get(i).ititre);
vue1.setText(Items.get(i).ivue);
return view1;
}
}
/*
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new AsyncCaller().execute();
}*/
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(annonces.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("/tChargement des annonces en cours ... ");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://www.waslup.pw/wp-admin/admin-ajax.php?action=do_ajax&fn=get_posts&count=10&key="+skey+"&cat="+scat+"&loc="+sloc);
HttpURLConnection httpuc = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpuc.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputstream));
String line ="";
while(line != null){
line = bf.readLine();
data= data + line;
}
JSONArray JA = null;
JA = new JSONArray(data);
annonces.Items.removeAll(annonces.Items);
for (int i=0 ; i<JA.length();i++){
JSONObject JO =(JSONObject) JA.get(i);
date =""+ JO.get("date");
loc =""+ JO.get("loc");
cat =""+ JO.get("Cat");
vue =""+ JO.get("vue");
titre =""+ JO.get("title");
id =""+ JO.get("Id");
annonces.Items.add(new annonce_item(id,date,loc,cat,vue,titre));
}
} catch (MalformedURLException e) {
} catch (JSONException e) {
} catch (IOException e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
final MyCustomAdapter myadpter = new MyCustomAdapter(Items);
ListView ls = (ListView) findViewById(R.id.listannonce);
ls.setAdapter(myadpter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView titre = (TextView) view.findViewById(R.id.titre);
Toast.makeText(getApplicationContext(), titre.getText(), Toast.LENGTH_LONG).show();
myadpter.notifyDataSetChanged();
TextView id2 = (TextView) view.findViewById(R.id.id);
Intent intent = new Intent(getBaseContext(), annonce_details.class);
intent.putExtra("id_from_annonces_activity", id2.getText());
startActivity(intent);
}
});
}
}
}
I reviewed your code and solved your problem.
There are two things need to discuss.
Your API providing the results according to localisation.If we change first two fields results will remain same and web service is fetching only one item with localisation 'oran'. But if we change localisation from 'oran' to 'alger' web service is displaying 4 results.
Here is the problem in your code.You are not concatenating your results properly in your data string. I have updated your code and now your code of AsyncCaller in announces Activity should be like:
Here is the code
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(annonces.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("/tChargement des annonces en cours ... ");
pdLoading.show();
}
#SuppressLint("NewApi")
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://www.waslup.pw/wp-admin/admin-ajax.php?action=do_ajax&fn=get_posts&count=10&key="+skey+"&cat="+scat+"&loc="+sloc);
HttpURLConnection httpuc = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpuc.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder total = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
total.append(line).append('\n');
}
JSONArray JA = null;
JA = new JSONArray(total.toString());
annonces.Items.removeAll(annonces.Items);
for (int i=0 ; i<JA.length();i++){
JSONObject JO =(JSONObject) JA.get(i);
date =""+ JO.get("date");
loc =""+ JO.get("loc");
cat =""+ JO.get("Cat");
vue =""+ JO.get("vue");
titre =""+ JO.get("title");
id =""+ JO.get("Id");
annonces.Items.add(new annonce_item(id,date,loc,cat,vue,titre));
}
} catch (MalformedURLException e) {
} catch (JSONException e) {
Log.d("js_ex:",e.toString());
} catch (IOException e) {
Log.d("io_ex:",e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
final MyCustomAdapter myadpter = new MyCustomAdapter(Items);
ListView ls = (ListView) findViewById(R.id.listannonce);
ls.setAdapter(myadpter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView titre = (TextView) view.findViewById(R.id.titre);
Toast.makeText(getApplicationContext(), titre.getText(), Toast.LENGTH_LONG).show();
myadpter.notifyDataSetChanged();
TextView id2 = (TextView) view.findViewById(R.id.id);
Intent intent = new Intent(getBaseContext(), annonce_details.class);
intent.putExtra("id_from_annonces_activity", id2.getText());
startActivity(intent);
}
});
}
}
In this code i added this part
StringBuilder total = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
total.append(line).append('\n');
}
JSONArray JA = null;
JA = new JSONArray(total.toString());

Is my Rss Reader app not working because there are too many parsers (Android Studio)?

I'm a high school student working for a magazine in South Korea known as Teen 10 Magazine. As an aspiring computer science major, I decided to make an RSS reader app for my magazine in order to showcase my skills for college applications (and also to create an app, which has always been my interest). Basically, I want to format my app to be similar to your typical news app (ex. CNN, BBC, etc).
Category Screen
In a DrawerLayout (as seen in the Category Screen), I decided to make a tab for each different category (such as News, Features, Entertainment, etc), including the Home category, which is where the categories the articles are under don't matter. When users click on each different tab, it gives them a list of articles that are categorized under that category. In order to get this data, I'm parsing the data to get the title (which is displayed in the list) and the link (which is set to an Intent so that users can access the article in the Web when it is clicked)
However, while some of the categories do work (Home, Lifestyle, Fashion), the rest of the categories are stuck in the loading screen for almost an infinite amount of time.
Example of loading category
I'm pretty sure that the codes of the categories that work and the categories that don't are the same (for reference, I copied and pasted and adjusted each different category accordingly, which could also be an issue but I'm not sure), and are getting their data from the appropriate sites.
Is it perhaps there are too many parsers (RssParser does the actual parsing and seven different "RssService"s use the parser to parse the data from each different category) for my app to work with? My app does seem to crash once in a while though...
I will post my codes below:
MainActivity.java:
package com.hfad.teen10magazine;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ShareActionProvider;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends Activity {
/* adds the fragment to the activity */
private ShareActionProvider shareActionProvider;
private String[] titles;
private ListView drawerList;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private int currentPosition = 0;
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code to run when an item in the navigation drawer gets clicked
selectItem(position);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
titles = getResources().getStringArray(R.array.titles);
drawerList = (ListView)findViewById(R.id.drawer);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
//Initialize the ListView
drawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, titles));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
//Display the correct fragment.
if (savedInstanceState != null) {
currentPosition = savedInstanceState.getInt("position");
setActionBarTitle(currentPosition);
} else {
selectItem(0);
}
//Create the ActionBarDrawerToggle
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.string.open_drawer, R.string.close_drawer) {
//Called when a drawer has settled in a completely closed state
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
//Called when a drawer has settled in a completely open state.
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.addDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
FragmentManager fragMan = getFragmentManager();
Fragment fragment = fragMan.findFragmentByTag("visible_fragment");
if (fragment instanceof TopFragment) {
currentPosition = 0;
}
if (fragment instanceof LifestyleFragment) {
currentPosition = 1;
}
if (fragment instanceof EntFragment) {
currentPosition = 2;
}
if (fragment instanceof NewsFragment) {
currentPosition = 3;
}
if (fragment instanceof FeaturesFragment) {
currentPosition = 4;
}
if (fragment instanceof AcademicsFragment) {
currentPosition = 5;
}
if (fragment instanceof FashionFragment) {
currentPosition = 6;
}
setActionBarTitle(currentPosition);
drawerList.setItemChecked(currentPosition, true);
}
}
);
}
private void selectItem(int position) {
// update the main content by replacing fragments
currentPosition = position;
Fragment fragment;
switch(position) {
case 1:
fragment = new LifestyleFragment();
break;
case 2:
fragment = new EntFragment();
break;
case 3:
fragment = new NewsFragment();
break;
case 4:
fragment = new FeaturesFragment();
break;
case 5:
fragment = new AcademicsFragment();
break;
case 6:
fragment = new FashionFragment();
break;
default:
fragment = new TopFragment();
}
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, fragment, "visible_fragment");
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
//Set the action bar title
setActionBarTitle(position);
//Close the drawer
drawerLayout.closeDrawer(drawerList);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = drawerLayout.isDrawerOpen(drawerList);
menu.findItem(R.id.action_share).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", currentPosition);
}
private void setActionBarTitle(int position) {
String title="";
titles=getResources().getStringArray(R.array.titles);
if (position == 0){
title = getResources().getString(R.string.app_name);
} else {
title = titles[position];
}
getActionBar().setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
shareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
setIntent("This is example text");
return super.onCreateOptionsMenu(menu);
}
private void setIntent(String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, text);
shareActionProvider.setShareIntent(intent);
}
}
RssItem.java:
package com.hfad.teen10magazine;
public class RssItem {
private final String title;
private final String link;
private final String pubDate;
public RssItem(String title, String link, String pubDate) {
this.title = title;
this.link = link;
this.pubDate = pubDate;
}
public String getTitle() {
return title;
}
public String getLink() {
return link;
}
public String getDate() {
return pubDate;
}
}
RssParser.java:
package com.hfad.teen10magazine;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
public class RssParser {
// We don't use namespaces
private final String ns = null;
public List<RssItem> parse(InputStream inputStream) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(inputStream, null);
parser.nextTag();
return readFeed(parser);
} finally {
inputStream.close();
}
}
private List<RssItem> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, null, "rss");
String title = null;
String link = null;
String pubDate = null;
List<RssItem> items = new ArrayList<RssItem>();
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("title")) {
title = readTitle(parser);
} else if (name.equals("link")) {
link = readLink(parser);
} else if (name.equals("pubDate")) {
pubDate = readDate(parser);
}
if (title != null && link != null && pubDate != null) {
RssItem item = new RssItem(title, link, pubDate);
items.add(item);
title = null;
link = null;
pubDate = null;
}
}
return items;
}
private String readLink(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "link");
String link = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "link");
return link;
}
private String readTitle(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "title");
return title;
}
private String readDate(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "pubDate");
String pubDate = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "pubDate");
return pubDate;
}
// For the tags title and link, extract their text values.
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
}
Constants.java:
package com.hfad.teen10magazine;
public class Constants {
public static final String TAG = "Teen10MagazineApp";
}
RssAdapter.java:
package com.hfad.teen10magazine;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class RssAdapter extends BaseAdapter {
/* puts the RSS items in a list */
private final List<RssItem> items;
private final Context context;
public RssAdapter(Context context, List<RssItem> items) {
this.items = items;
this.context = context;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.rss_item, null);
holder = new ViewHolder();
holder.itemTitle = (TextView) convertView.findViewById(R.id.itemTitle);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemTitle.setText(items.get(position).getTitle());
return convertView;
}
static class ViewHolder {
TextView itemTitle;
}
}
Along with the main codes, for the sake of time, I will post the codes of one category that works (the fragment it is placed in and the RssService used to get it) and the codes of one that doesn't work. If you need more information or codes, please contact me and I will be happy to provide information:
LifeStyleFragment.java (Works):
package com.hfad.teen10magazine;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.util.List;
public class LifestyleFragment extends Fragment implements AdapterView.OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_layout, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
startService();
} else {
// If we are returning from a configuration change:
// "view" is still attached to the previous view hierarchy
// so we need to remove it and re-attach it to the current one
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService_Lifestyle.class);
intent.putExtra(RssService_Lifestyle.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
#SuppressWarnings("unchecked")
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
List<RssItem> items = (List<RssItem>) resultData.getSerializable(RssService_Lifestyle.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occurred while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
};
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
RssService_Lifestyle.java:
package com.hfad.teen10magazine;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import org.xmlpull.v1.XmlPullParserException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
public class RssService_Lifestyle extends IntentService {
/* parse the rss feed on lifestyle and send the list of items to LifestyleFragment */
private static final String RSS_LINK = "http://www.teen10mag.com/category/lifestyle/feed/";
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService_Lifestyle() {
super("RssService_Lifestyle");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try {
RssParser parser = new RssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
} catch (XmlPullParserException | IOException e) {
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link) {
try {
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e) {
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
AcademicsFragment.java (Doesn't work):
package com.hfad.teen10magazine;
import java.util.List;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AcademicsFragment extends Fragment implements AdapterView.OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_layout, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
startService();
} else {
// If we are returning from a configuration change:
// "view" is still attached to the previous view hierarchy
// so we need to remove it and re-attach it to the current one
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService_Academics.class);
intent.putExtra(RssService_Academics.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
#SuppressWarnings("unchecked")
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
List<RssItem> items = (List<RssItem>) resultData.getSerializable(RssService_Academics.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occurred while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
}
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
RssService_Academics.java:
package com.hfad.teen10magazine;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
public class RssService_Academics extends IntentService {
/* parse the rss feed on academics and send the list of items to AcademicsFragment */
private static final String RSS_LINK = "http://www.teen10mag.com/category/academics/feed/";
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService_Academics() {
super("RssService_Academics");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try {
RssParser parser = new RssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
} catch (XmlPullParserException | IOException e) {
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link) {
try {
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e) {
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
This is my first question, so I tried to be as detailed as possible. If my explanations were unreasonably lengthy, I do apologize. This is also my first time coding something this extensive, so forgive me if I seem to make amateur mistakes...
Thank you in advance for all of your help!!
[EDIT]
When I click on the category that doesn't work, the logcat turns up like this:
09-21 19:29:59.237 1541-1866/system_process W/ActivityManager: Unable to start service Intent { cmp=com.hfad.teen10magazine/.RssService_News (has extras) } U=0: not found
09-21 19:30:13.209 2808-2808/com.hfad.teen10magazine I/Choreographer: Skipped 31 frames! The application may be doing too much work on its main thread.
09-21 19:30:21.122 2808-2814/com.hfad.teen10magazine W/art: Suspending all threads took: 13.025ms`

Run on MarashMallow, application crashed due to Cursor Index Out Of Bounds Index z requested, with a size of z

Below the code I used:
Activitymain_txt.java
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.example.apple.qs.Activity.db.Constant;
import com.example.apple.qs.Activity.db.DatabaseHandler_txt;
import com.example.apple.qs.Activity.fragment.ContactFragment;
import com.example.apple.qs.Activity.fragment.FragmentAdapter;
import com.example.apple.qs.Activity.fragment.MessageFragment;
import com.example.apple.qs.Activity.db.model.Message;
import com.example.apple.qs.Activity.db.Store.ContactStore;
import com.example.apple.qs.Activity.db.Store.MessageStore;
import java.util.ArrayList;
import com.example.apple.qs.Activity.R;
import java.util.List;
public class ActivityMain_txt extends AppCompatActivity {
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar toolbar;
private DrawerLayout drawerLayout;
public static MessageFragment f_message;
private ContactFragment f_contact;
public FloatingActionButton fab;
private Toolbar searchToolbar;
private boolean isSearch = false;
private ViewPager viewPager;
private DatabaseHandler_txt db;
public ContactStore contacsStore;
public MessageStore messageStore;
public static List<Message> messageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_txt);
setupDrawerLayout();
db = new DatabaseHandler_txt(getApplicationContext());
toolbar = (Toolbar) findViewById(R.id.toolbar_viewpager);
searchToolbar = (Toolbar) findViewById(R.id.toolbar_search);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ActivityNewMessage_txt.class);
startActivity(i);
}
});
//initToolbar();
prepareActionBar(toolbar);
contacsStore = new ContactStore(getApplicationContext());
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
closeSearch();
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 0) {
fab.show();
} else {
fab.hide();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// for system bar in lollipop
Window window = this.getWindow();
if (Constant.getAPIVerison() >= 5.0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
}
}
private void setupViewPager(ViewPager viewPager) {
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
if (f_message == null) {
f_message = new MessageFragment();
}
if (f_contact == null) {
f_contact = new ContactFragment();
}
adapter.addFragment(f_message, "MESSAGE");
adapter.addFragment(f_contact, "CONTACT");
viewPager.setAdapter(adapter);
}
private void prepareActionBar(Toolbar toolbar) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(getResources().getColor(isSearch ? android.R.color.darker_gray : R.color.colorPrimary));
}
if (!isSearch) {
settingDrawer();
}
}
private void settingDrawer() {
mDrawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close ) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(mDrawerToggle);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView view = (NavigationView) findViewById(R.id.nav_view);
view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
actionDrawerMenu(menuItem.getItemId());
return true;
}
});
}
private void actionDrawerMenu(int itemId) {
switch (itemId) {
case R.id.nav_notif:
Intent i = new Intent(getApplicationContext(), ActivityNotificationSettings_txt.class);
startActivity(i);
break;
case R.id.nav_rate:
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
break;
case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About");
builder.setMessage(getString(R.string.about_text));
builder.setNeutralButton("OK", null);
builder.show();
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (!isSearch) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(isSearch ? R.menu.menu_search_toolbar_txt : R.menu.menu_main_txt, menu);
if (isSearch) {
//Toast.makeText(getApplicationContext(), "Search " + isSearch, Toast.LENGTH_SHORT).show();
final SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setIconified(false);
if (viewPager.getCurrentItem() == 0) {
search.setQueryHint("Search message...");
} else {
search.setQueryHint("Search contact...");
}
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter(s);
} else {
f_contact.mAdapter.getFilter().filter(s);
}
return true;
}
});
search.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
closeSearch();
return true;
}
});
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search: {
isSearch = true;
searchToolbar.setVisibility(View.VISIBLE);
prepareActionBar(searchToolbar);
supportInvalidateOptionsMenu();
return true;
}
case android.R.id.home:
closeSearch();
return true;
case R.id.action_refresh: {
if(viewPager.getCurrentItem()==0){
new RefreshMessage().execute("");
}else{
new RefreshContact().execute("");
}
}
default:
return super.onOptionsItemSelected(item);
}
}
private void closeSearch() {
if (isSearch) {
isSearch = false;
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter("");
} else {
f_contact.mAdapter.getFilter().filter("");
}
prepareActionBar(toolbar);
searchToolbar.setVisibility(View.GONE);
supportInvalidateOptionsMenu();
}
}
private long exitTime = 0;
public void doExitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, R.string.press_again_exit_app, Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
public void onResume(){
try{
Uri uri = MessageStore.URI;
changeObserver = new ChangeObserver();
this.getContentResolver().registerContentObserver(uri, true, changeObserver);
}catch (Exception e){
}
super.onResume();
}
#Override
protected void onRestart() {
try{
f_message.bindView();
}catch (Exception e){
}
super.onRestart();
}
#Override
public void onPause(){
this.getContentResolver().unregisterContentObserver(changeObserver);
super.onPause();
}
#Override
public void onBackPressed() {
doExitApp();
}
private ChangeObserver changeObserver;
// wil update only when there a change
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
try{
if(!loadRunning) {
loadRunning = true;
changeLoad = new ChangeLoad();
changeLoad.execute("");
}
}catch (Exception e){
}
}
}
private ChangeLoad changeLoad;
private boolean loadRunning = false;
private class ChangeLoad extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
messageStore.update();
return null;
}
#Override
protected void onPostExecute(String s) {
loadRunning = false;
messageList = messageStore.getAllconversation();
f_message.bindView();
super.onPostExecute(s);
}
}
private class RefreshMessage extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_message.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(100);
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_message.onStopRefreshLoading();
super.onPostExecute(s);
}
}
private class RefreshContact extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_contact.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(10);
db.truncateDB();
contacsStore = new ContactStore(getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_contact.onStopRefreshLoading();
super.onPostExecute(s);
}
}
}
ContactStore.java
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import com.example.apple.qs.Activity.db.DatabaseHandler_txt;
import com.example.apple.qs.Activity.db.model.Contact;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ContactStore {
private static Context ctx;
private static ContentResolver sResolver;
private static final String TAG = "ContactStore";
private DatabaseHandler_txt db;
private List<Contact> allContacts = new ArrayList<>();
public ContactStore(Context context) {
ctx = context;
sResolver = ctx.getContentResolver();
db = new DatabaseHandler_txt(context);
// populate contact to database when first time
if(db.isDatabaseEmpty()){
//init contact data
retriveAllContact();
// save to database
db.addListContact(allContacts);
}else{
allContacts.clear();
allContacts = db.getAllContacts();
}
Collections.sort(allContacts, new Comparator<Contact>() {
#Override
public int compare(Contact c1, Contact c2) {
String l1 = c1.name.toLowerCase();
String l2 = c2.name.toLowerCase();
return l1.compareTo(l2);
}
});
}
public Contact getByRecipientId(long recipientId) {
Cursor addrCursor = sResolver.query(Uri.parse("content://mms-sms/canonical-address/" + recipientId), null,null, null, null);
addrCursor.moveToFirst();
String number = addrCursor.getString(0); // we got number here
number=number.replace(" ", "");
number=number.replace("-", "");
Contact c = db.findContactByNumber(number);
return c;
}
public List<Contact> getAllContacts() {
return allContacts;
}
public Contact getDetailsContact(Contact c){
return db.getDetailsContact(c);
}
private void retriveAllContact() {
ContentResolver cr = ctx.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
long id = cur.getLong(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String photoId;
try {
photoId = cur.getString(cur.getColumnIndex(ContactsContract.Data.PHOTO_URI));
} catch (Exception e) {
photoId = "";
}
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
List<String> phones = new ArrayList<>();
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id+""}, null);
while (cursor.moveToNext()){
String p = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
p=p.replace(" ", "");
p=p.replace("-", "");
if(!phones.contains(p)){
phones.add(p);
}
}
Contact c = new Contact();
c.id = id;
c.name = name;
c.photoUri = photoId;
c.allPhoneNumber = phones;
allContacts.add(c);
cursor.close();
}
}
}
}
}
MessageStore.java
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.example.apple.qs.Activity.Activity.ActivityMain_txt;
import com.example.apple.qs.Activity.db.Constant;
import com.example.apple.qs.Activity.db.SharedPref_txt;
import com.example.apple.qs.Activity.db.model.Contact;
import com.example.apple.qs.Activity.db.model.Message;
import com.example.apple.qs.Activity.receiver.BedgeNotifier;
import java.util.ArrayList;
import java.util.List;
public class MessageStore {
public static final Uri URI = Uri.parse("content://mms-sms/conversations?simple=true");
public static final Uri URI_SMS = Uri.parse("content://sms");
private ContentResolver mResolver;
public static List<Message> allconv = new ArrayList<>();
static Cursor cursor = null;
private ContactStore contactStore;
private ActivityMain_txt act;
private Context ctx;
private static final String TAG = "/ConvStore";
public static final String[] PROJECTION = new String[] {
"_id",
"date",
"message_count",
"recipient_ids",
"snippet",
"read",
"type"
};
public MessageStore(ActivityMain_txt act) {
this.ctx = act.getApplicationContext();
this.act = act;
contactStore = new ContactStore(ctx);
mResolver = ctx.getContentResolver();
allconv = new ArrayList<>(20);
cursor = mResolver.query(URI,
PROJECTION,
null,
null,
"date DESC"
);
// cursor.registerContentObserver(new ChangeObserver());
retrieveAllConversation();
}
private void retrieveAllConversation(){
update();
}
public void update() {
int unread_counter = 0;
allconv.clear();
cursor.requery();
if(cursor == null || cursor.getCount() == 0) {
return;
}
if (cursor!= null && cursor.moveToFirst()){
cursor.moveToFirst();
do {
Message conv = new Message();
conv.threadId = cursor.getLong(0);
conv.date = cursor.getLong(1);
conv.msgCount = cursor.getInt(2);
conv.snippet = cursor.getString(4);
conv.read = cursor.getInt(5) == 1;
if(!conv.read){
unread_counter++;
}
if(!allconv.contains(conv)) {
allconv.add(conv);
}
int recipient_id = cursor.getInt(3);
Contact recipient = contactStore.getByRecipientId(recipient_id);
conv.contact = recipient;
} while(cursor.moveToNext()); }
SharedPref_txt.setIntPref(Constant.I_KEY_UNREAD_COUNT, unread_counter, ctx);
BedgeNotifier.setBadge(ctx, unread_counter);
}
public List<Message> getAllconversation() {
return allconv;
}
public void markAsRead(long threadId) {
ContentValues cv = new ContentValues(1);
cv.put("read", 1);
mResolver.update(URI_SMS,
cv,
"read=0 AND thread_id=" + threadId,
null
);
}
/**
* Find conversation by phone number
*
* #return conversation id, new id will be assigned if not exist
**/
public static long getOrCreateConversationId(Context context, String number){
long cid = -1;
Uri uri = Uri.parse("content://sms");
Cursor cur = context.getContentResolver().query(
uri,
new String[] {"thread_id"},
"address =?",
new String[] { number},
null);
if(cur!=null){
if(cur.moveToFirst()){
cid = cur.getLong(0);
}
cur.close();
}
// Allocate new conversation_id if no match
if(cid==-1){
cur = context.getContentResolver().query(
uri,
new String[] {"thread_id"},
null,
null,
"thread_id DESC ");
if(cur!=null){
if(cur.moveToFirst()){
// new conversation_id = Max(conversation_id)+1
cid = cur.getLong(0)+1;
}
cur.close();
}
// no entry in the database, start the id from 10 in case smaller numbers are reserved
if(cid==-1){
cid=10;
}
}
return cid;
}
public static boolean deleteMessage(Context context, String threadId) {
int result;
result = context.getContentResolver().delete(URI_SMS, "thread_id = ?", new String[] { threadId });
if (result > 0) {
return true;
}
return false;
}
}
Log Message
I have no idea how to solve the issue of android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0.
I have tried adding the following code at the update() in the MessageStore.java:
if (cursor!= null && cursor.moveToFirst())
but yet no avail. Can anyone helps me? Application crashes every time I load it.
Thank you in advance.
Exception is raised in method getRecepientById() of ContactStore. It seems that addrCursor has no records.
Add a check if addrCursor has any records to be safe. In case there's no recepient return null.
Cursor addrCursor = sResolver.query(Uri.parse("content://mms-sms/canonical-address/" + recipientId), null,null, null, null);
if (addrCursor.moveToFirst()) {
String number = addrCursor.getString(0); // we got number here
number = number.replace(" ", "");
number = number.replace("-", "");
Contact c = db.findContactByNumber(number);
return c;
} else {
return null;
}

navigation drawer not working after asynctask

I am using navigation drawer with asynctask in one of the fragments. As soon as I click the element in navigation drawer to start that fragment, my navigation drawer stops working even after the asynctask is finished. I am able to click on navigation drawer and open it , but whenever I click on some other item in navigation drawer, it just closes without loading that fragment associated with that item in nav drawer.
main activity code:
package com.example.home;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.http.cookie.Cookie;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.fmapp.R;
import com.example.fmapp.StartActivity;
import com.example.fmapp.R.id;
import com.example.fmapp.R.layout;
import com.example.fmapp.R.menu;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
#SuppressLint("NewApi")
public class Home extends Activity implements ActionBar.OnNavigationListener{
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerTitles;
static ProgressBar bar;
private String mCurrentPhotoPath;
private final static int FILECHOOSER_RESULTCODE=1;
//public AsyncHttpUpload uploadThread = null;
public ArrayAdapter<String> adapter = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Log.i("start","started");
/*
if ((savedInstanceState != null) && (savedInstanceState.getString("currPath")) != null){
mCurrentPhotoPath = savedInstanceState.getString("currPath");
}
*/
bar = (ProgressBar) this.findViewById(R.id.progressBar);
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
if (UserInfo.userId == null){
//fetchUserData();
}
else{
//UserInfo.populateSpinner(adapter);
}
mTitle = mDrawerTitle = getTitle();
mDrawerTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mDrawerTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
//MenuItem item = menu.findItem(R.id.accounts_spinner);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_logout:
logOut();
return true;
case R.id.action_change_pw:
Intent intent = new Intent(this, ChangePw.class);
this.startActivity(intent);
return true;
// case R.id.accounts_spinner:
// Log.i("spinner","spinner click");
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("NewApi")
private void logOut() {
// TODO Auto-generated method stub
Log.i("logout","to logout");
//clear data
UserInfo.chosenAccount = null;
//clear client cookies
String cookieString = "";
Log.i("number of cookies",Integer.toString(StartActivity.cookieManager.getCookieStore().getCookies().size()));
if(StartActivity.cookieManager.getCookieStore().getCookies().size() != 0){
//HttpCookie cookie = (HttpCookie) StartActivity.cookieManager.getCookieStore().getCookies().toArray()[0];
//HttpCookie cookie = (HttpCookie) StartActivity.cookieManager.getCookieStore().getCookies().get(0);
int login_cookie_index = 0;
List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
//TODO: search for ltsid cookie
for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
login_cookie_index = cookie_iter;
break;
}
}
HttpCookie cookie = cookieList.get(login_cookie_index);
cookieString = cookie.getValue();
StartActivity.cookieManager.getCookieStore().removeAll();
}
//clear server sessionId
JSONObject data = new JSONObject();
JSONObject name = new JSONObject();
JSONArray arg = new JSONArray();
try{
data.put("requestCommand", "LogOut");
name.put("name","sessionId");
name.put("type", "String");
name.put("value", cookieString);
arg.put(name);
data.put("args", arg);
String finaldata = data.toString();
new AsyncHttpLogout(this).execute(finaldata);
} catch (JSONException e2) {
e2.printStackTrace();
}
this.finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
finish();
return true;
} //TODO:can go forward
}
return super.onKeyDown(keyCode, event);
}
#SuppressLint("NewApi")
private void fetchUserData() {
int login_cookie_index = 0;
List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
//TODO: search for ltsid cookie
for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
login_cookie_index = cookie_iter;
break;
}
}
HttpCookie cookie = cookieList.get(login_cookie_index);
JSONObject data = new JSONObject();
JSONObject sid = new JSONObject();
JSONArray arg = new JSONArray();
try {
data.put("requestCommand","FetchInfo");
sid.put("name","sessionId");
sid.put("type", "String");
sid.put("value", cookie.getValue());
arg.put(sid);
data.put("args", arg);
} catch (JSONException e2) {
e2.printStackTrace();
}
Log.i("fetch data",data.toString());
String finaldata = data.toString();
//View mySpinnerView = this.findViewById(R.id.accounts_spinner);
new AsyncGetAccountInfo(this,adapter).execute(finaldata);
}
#Override
public boolean onNavigationItemSelected(int position, long itemId) {
Log.i("arg0",Integer.toString(position));
//Log.i("arg1",Long.toString(itemId));
//UserInfo.chosenAccount = UserInfo.accountArray.get(position);
//TODO: fix default account
return false;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("currPath", mCurrentPhotoPath);
//savedInstanceState.
// etc.
}
/*
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
*/
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
if (position ==0){
Fragment fragment = new OrderForm();
Bundle args = new Bundle();
args.putInt(OrderForm.ARG_LIST_INDEX, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position ==1){
Fragment fragment = new ServicesGrid();
Bundle args = new Bundle();
args.putInt(ServicesGrid.ARG_LIST_INDEX, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position ==2){
Fragment fragment = new UserProfile();
Bundle args = new Bundle();
args.putInt(UserProfile.ARG_LIST_INDEX, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position ==3){
Fragment fragment = new OrderList();
Bundle args = new Bundle();
args.putInt(OrderList.ARG_LIST_INDEX, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position ==4){
}
else{
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
//((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
The problematic fragment is with position =3, the fragment's code:
package com.example.home;
import java.io.File;
import java.io.IOException;
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.fmapp.R;
import com.example.fmapp.StartActivity;
import android.app.Fragment;
import android.app.ListFragment;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class OrderList extends ListFragment {
public static final String ARG_LIST_INDEX = "planet_number";
public OrderList(){
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_orderlist, container, false);
int i = getArguments().getInt(ARG_LIST_INDEX);
fetchOrderInfo();
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
//((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
public void fetchOrderInfo() {
// TODO Auto-generated method stub
int login_cookie_index = 0;
List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
//TODO: search for ltsid cookie
for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
login_cookie_index = cookie_iter;
break;
}
}
HttpCookie cookie = cookieList.get(login_cookie_index);
JSONObject data = new JSONObject();
JSONObject sid = new JSONObject();
JSONArray arg = new JSONArray();
try {
data.put("requestCommand","GetRequestInfo");
sid.put("name","sessionId");
sid.put("type", "String");
sid.put("value", cookie.getValue());
arg.put(sid);
data.put("args", arg);
} catch (JSONException e2) {
e2.printStackTrace();
}
Log.i("fetch data",data.toString());
String finaldata = data.toString();
//View mySpinnerView = this.findViewById(R.id.accounts_spinner);
new AsyncFetchUserOrders(getActivity(),this).execute(finaldata);
return;
}
/*
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("list click","list item click");
}
*/
public void populateAdapter(ArrayList<OrderObj> arrayOrderObj) {
ArrayAdapter<OrderObj> OrderList = new OrderAdapter(getActivity(), arrayOrderObj);
setListAdapter(OrderList);
}
}
Note that if I comment out asynctask line, the nav drawer works fine.
Now the asynctask code:
package com.example.home;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import com.example.fmapp.GlobalVars;
import com.example.fmapp.JsonUtil;
import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AsyncFetchUserOrders extends AsyncTask<String,Boolean,Integer> {
protected static String USER_SERVER = GlobalVars.USER_SERVER;
private int errorCode = -1;
ProgressBar bar = Home.bar;
private Context mainContext;
private OrderList orderFragment;
//private Arra
private ArrayAdapter<String> adapter;
public ArrayList<OrderObj> arrayOrderObj = new ArrayList<OrderObj>();// TODO: populate this shit
private String toastMsg = null;
public AsyncFetchUserOrders(Context mainContext, OrderList orderFragment) {
this.mainContext = mainContext;
this.orderFragment = orderFragment;
}
protected void onPreExecute(){
bar.setVisibility(View.VISIBLE);
}
#SuppressLint("NewApi")
#Override
protected Integer doInBackground(String... params) {
URL url = null;
Log.i("req data",params[0]);
try {
url = new URL(USER_SERVER);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
e1.printStackTrace();
}
urlConnection.setReadTimeout( 10000 /*milliseconds*/ );
urlConnection.setConnectTimeout( 15000 /* milliseconds */ );
//urlConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
try {
urlConnection.setDoOutput(true);
try {
urlConnection.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
urlConnection.connect();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(params[0]);
writer.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
//response:
try { //parse errorCode
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String response = urlConnection.getResponseMessage();
/*
InputStream responseStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
Log.i("line",line);
}
responseStreamReader.close();
*/
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer stringBuilder = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine);
}
in.close();
String resp = stringBuilder.toString();
Log.i("resp",resp);
processResp(resp);
}
} catch (IOException e) {
e.printStackTrace();
}
}
finally {
urlConnection.disconnect();
}
return 1;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Integer result) {
//Log.i("postexec","in post execute");
bar.setVisibility(View.GONE);
Toast toast = Toast.makeText(mainContext, toastMsg, Toast.LENGTH_SHORT);
toast.show();
if (JsonUtil.authSucess == false){
}
else{
// Imp TODO : get to new Activity
Log.i("ltid","populate spinner");
//IMP TODO :UserInfo.populateSpinner(adapter);
JsonUtil.authSucess = false;
/*
if (arrayOrderObj != null){
ArrayAdapter<OrderObj> OrderList = new OrderAdapter(mainContext, arrayOrderObj);
orderFragment.setListAdapter(OrderList);
}*/
}
//this.cancel(true);
}
/*
public void onStop() {
//super.onStop();
if(this!=null){
this.cancel(true);
}
}
*/
private void processResp(String resp) {
errorCode = JsonUtil.processRespForErrorCode(resp);
if (errorCode == 0){
JsonUtil.authSucess = true;
toastMsg = "Order info received";
//TODO: parse JSON and populate user orderinfo info
Log.i("orders", "to populate Order");
JsonUtil.populateOrderInfo(resp,arrayOrderObj);
//Log.i("fname",UserInfo.chosenAccount.firstName);
/*
ArrayAdapter<OrderObj> OrderList = new OrderAdapter(mainContext, arrayOrderObj);
orderFragment.setListAdapter(OrderList);
*/
//orderFragment.populateAdapter(arrayOrderObj);
}
else{
toastMsg = "Something wrong";
}
}
}
Once again, nothing fancy here. still cant figure out what is making the navigation drawer to just close and not start the fragment, if it is clicked on item to start another fragment.
Thanks.
I guess it will be the Home.bar covers your fragment? Maybe you should use ProgressBar.show() or ProgressBar.dismiss() to control the visibility of the progressbar

Categories

Resources