keep data between fragment - java

I'm trying to keep data(PID) from fragmentscan to fragment maintenance using arguments,
but the data always null in my Log.d("tag", "PID SCAN: " + data);
whats wrong with my arguments?
this is my code
public class FragmentScan extends Fragment {
TextView tvPid;
TextView txtName;
TextView txtPrice;
TextView txtDesc;
TextView txtSpec;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://10.0.3.2/skripsi/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_SPESIFICATION = "spesification";
// Progress Dialog
private static final String PID_KEY = "tvPid";
private static final String NAME_KEY = "tvName";
private static final String PRICE_KEY = "tvPrice";
private static final String DESCRIPTION_KEY = "tvDesc";
private static final String SPESIFICATION_KEY = "tvSpec";
private String mPid=null;
private String mName=null;
private String mPrice=null;
private String mDesc=null;
private String mSpec=null;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ZZZ", "ada di oncreateView");
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_layout_four, container, false);
tvPid = (TextView) rootView.findViewById(R.id.tvPid);
txtName = (TextView) rootView.findViewById(R.id.tvName);
txtPrice = (TextView) rootView.findViewById(R.id.tvPrice);
txtDesc = (TextView) rootView.findViewById(R.id.tvDesc);
txtSpec = (TextView) rootView.findViewById(R.id.tvSpec);
Btngetdata = (Button)rootView.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new FragmentMaintenance();
Bundle data = new Bundle();
data.putString("pid", mPid);
fragment.setArguments(data);
FragmentManager frgManager = getFragmentManager();
Log.d("tag", "PID SCAN: " + data);
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
}
});
Button scanBtn = (Button) rootView.findViewById(R.id.btnScan);
//in some trigger function e.g. button press within your code you should add:
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity(), "ERROR:" + e, Toast.LENGTH_LONG).show();
}
}
});
if (savedInstanceState != null) {
Log.d("ZZZ", "ada di di dlm if saved");
mPid = savedInstanceState.getString(PID_KEY);
mName = savedInstanceState.getString(NAME_KEY);
mPrice = savedInstanceState.getString(PRICE_KEY);
mDesc = savedInstanceState.getString(DESCRIPTION_KEY);
mSpec = savedInstanceState.getString(SPESIFICATION_KEY);
tvPid.setText(mPid);
txtName.setText(mName);
txtPrice.setText(mPrice);
txtDesc.setText(mDesc);
txtSpec.setText(mSpec);
}
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Log.d("ZZZ", "Ada di mainactivity");
if (requestCode == 0) {
TextView pid = (TextView) getActivity().findViewById(R.id.tvPid);
if (resultCode == Activity.RESULT_OK) {
pid.setText(intent.getStringExtra("SCAN_RESULT"));
new GetProductDetails(getActivity()).execute(pid.getText().toString());
} else if (resultCode == Activity.RESULT_CANCELED) {
pid.setText("Scan cancelled.");
}
}
}
class GetProductDetails extends AsyncTask<String, Void, String[]> {
/**
* Before starting background thread Show Progress Dialog
*/
private Context mContext;
public GetProductDetails(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
*/
protected String[] doInBackground(String... string) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", string[0]));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
Log.d("ZZZ", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
String[] result = {Integer.toString(success), product.getString(TAG_NAME), > product.getString(TAG_PRICE),
product.getString(TAG_DESCRIPTION),
product.getString(TAG_SPESIFICATION)};
// // display product data in EditText
// txtName.setText(product.getString(TAG_NAME));
// txtPrice.setText(product.getString(TAG_PRICE));
// txtDesc.setText(product.getString(TAG_DESCRIPTION));
Log.d("ZZZ", result[0]);
return result;
} else {
Log.d("ZZZ", Integer.toString(success));
String[] result = {Integer.toString(success)};
return result;
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String[] results) {
// dismiss the dialog once got all details
pDialog.dismiss();
if (results[0] != null) {
Log.d("ZZZ", "SUCCESS" + results[0]);
if (results[0].matches("1")) {
Log.d("ZZZ", "SUCCESS " + results[0]);
TextView name = (TextView) getActivity().findViewById(R.id.tvName);
name.setText(results[1]);
TextView price = (TextView) getActivity().findViewById(R.id.tvPrice);
price.setText(results[2]);
TextView desc = (TextView) getActivity().findViewById(R.id.tvDesc);
desc.setText(results[3]);
TextView spec = (TextView) getActivity().findViewById(R.id.tvSpec);
spec.setText(results[4]);
} else if (results[0].matches("-1")) {
Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show();
} else{
Log.d("ZZZ", "UNKNOWN ERROR");
}
}
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save state information with a collection of key-value pairs
// 4 lines of code, one for every count variable
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(PID_KEY, tvPid.getText().toString());
savedInstanceState.putString(NAME_KEY, txtName.getText().toString());
savedInstanceState.putString(PRICE_KEY, txtPrice.getText().toString());
savedInstanceState.putString(DESCRIPTION_KEY, txtDesc.getText().toString());
savedInstanceState.putString(SPESIFICATION_KEY, txtSpec.getText().toString());
}
}
This my activity
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
SharedPreferences preferences;
String pref;
List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = this.getSharedPreferences(Config.PREFERENCES, MODE_PRIVATE);
pref = preferences.getString(Config.SESSION,null);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Add Drawer Item to dataList
dataList.add(new DrawerItem("Scanner", R.drawable.ic_action_email));
dataList.add(new DrawerItem("Schedule", R.drawable.ic_action_good));
dataList.add(new DrawerItem("Games", R.drawable.ic_action_gamepad));
dataList.add(new DrawerItem("Logout", R.drawable.ic_action_about));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
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);
}
}
#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;
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 0:
fragment = new FragmentScan();
break;
case 1:
fragment = new FragmentSchedule();
break;
case 2:
fragment = new FragmentThree();
args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 3:
logout();
Intent in = new Intent(this, LoginActivity.class);
startActivity(in);
finish();
return;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
SelectItem(position);
}
}
//In the same activity you’ll need the following to retrieve the results:
private void logout(){
//TODO delete cookie from db
SharedPreferences.Editor editor = preferences.edit();
editor.remove(Config.SESSION);
editor.remove(Config.USERNAME);
editor.commit();
}
i hope someone can help me to solving this,
thanks before.

I think it's supposed to be not null, perhaps you just didn't retrieve the value properly.
In your logging code, you used:
Log.d("tag", "PID SCAN: " + data);
but actually you stored the pid using:
data.putString("pid", mPid);
which means, you should use key pid to get the value from the bundle, like:
Log.d("tag", "PID SCAN: " + data.getString("pid"));
EDIT:
If it is a process ID you are trying to get, try to look at android.os.Process.myPid();
If pid is your own pre-defined variable (containing something else),
then you need to pass it when you create the fragment like the following:
fragment = new FragmentScan();
args.putString("pid", YOUR_TV_PID_VALUE);
and from the other side (FragmentScan), you can use getArguments() to get the Bundle, and from there, just use getString("pid").
UPDATE:
After reading your code more, it seems you got the cycle a little bit tangled.
but one quick suggestion is: why don't you try it like the following
data.putString("pid", tvPid.getText());
In you original code, your pid in savedInstanceState supposed to be exist after you perform click on scanBtn, finish/cancel the scanning. But I think your code flow is a little bit tangled.
Read here that onSaveInstanceState is called to retrieve per-instance state from an activity before being killed.
=> That means, before you open another intent (performed by scanBtn), onSaveInstanceState is called and storing empty value of the tvPid. And when the main intent is resumed, it gets that bundle which contains empty string of pid. But it should be "", not null.

Related

Load JSON arraylist in separate class and load in another activity

I am trying to load some items from JSON, I am able to get and parse the JSON and load it up in listview when using one activity. However, I want to use a LoadJSON.class to load the JSON, and then the activity can call the json passed and show it in the listview in that activity.
Here is what I have tried:
SongsManager.class
public class SongsManager {
private String TAG = SongsManager.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxxxx.com/jame/mp3/songlist.json";
private List<SolTracks> solTracksList;
private ProgressDialog pDialog;
private final Activity activity;
public SongsManager(Activity activity) {
this.activity = activity;
solTracksList = new ArrayList<>();
pDialog = new ProgressDialog(activity);
fetchSongs();
}
private void fetchSongs() {
pDialog.setMessage("Fetching Playlist...");
pDialog.show();
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(API_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "Responser = " + response.toString());
pDialog.hide();
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
String songTitle = movieObj.getString("title");
String songId = movieObj.getString("id");
String streamUrl = movieObj.getString("stream_url");
SolTracks m = new SolTracks(songTitle, songId, streamUrl);
solTracksList.add(m);
Collections.sort(solTracksList, new TrackComparator());
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
pDialog.hide();
Snackbar snackbar = Snackbar
.make(activity.findViewById(android.R.id.content), "PLEASE CHECK YOUR INTERNET", Snackbar.LENGTH_LONG)
.setAction("DISMISS", new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Changing snackbar background
snackbar.getView().setBackgroundColor(ContextCompat.getColor(activity, R.color.colorPrimary));
// Changing message text color
snackbar.setActionTextColor(Color.YELLOW);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
});
req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
public List<SolTracks> getList() {
return solTracksList;
}
Activity class
public class TheMain1 extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
private String TAG = TheMain1.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxx.com/jame/mp3/songlist.json";
private ListView listView;
private SolTracksAdapter adapter;
private ProgressDialog pDialog;
private List<SolTracks> songslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.track_list_view);
songslist = new ArrayList<>();
SongsManager songsManager = new SongsManager(this);
songslist = songsManager.getList();
adapter = new SolTracksAdapter(this, songslist);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SolTracks track = songslist.get(position);
final String stream_url = track.stream_url;
final String id_url = track.id;
Intent intent = new Intent(TheMain1.this, PlayerActivity.class);
intent.putExtra("songPosition", position);
intent.putExtra("streamUrl", stream_url);
startActivity(intent);
}
}
);
}
As it is right now, I know the JSON is loaded from SongsManager, but its just not displaying in the listview of the Activity class. Can anyone help, and show what I'm doing wrong? Thanks
I was able to fix this by implementing Parcelable to send the list to the receiving activity.
public class SolTracks implements Parcelable {
public String title;
public String id;
public String stream_url;
}
Sending the list from the Activity A:
Intent intent = new Intent(TheMain.this, PlayerActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", solTracksList);
intent.putExtras(bundle);
intent.putExtra("songPosition", position);
startActivity(intent);
and then receiving in Activity B:
Bundle extras = getIntent().getExtras();
if (extras != null) {
songPosition = extras.getInt("songPosition");
trackList = extras.getParcelableArrayList("mylist");
}

Save radio button state w/button in Fragment and load upon opening app

So I am creating an app where when you first open it you have the option to use WiFi or Data to retrieve the data with oAuth2 (Still need to figure this out). However, I also have a settings button in my Nav Drawer that has a radio group with an enable or disable as far as using data. If the person says to enable Data, I turn their WiFi off (I shouldn't do this) I should be checking for connection state and whenever the connection equals Mobile Data then start uploading and if they click disable check for when the connection is WiFi and start uploading. However, I don't know how to do that currently so unless someone smarter than me can let me know now, that is how it is.
However, I am having an issue with my onClick on the save button saving the button state and then loading that state/decision upon opening the app. Furthermore, it is set as disabled by default, however, if the user clicks "Use Cell" in the app start up pop up, I would like to change that value.
I would really prefer some help in learning how to do this stuff, so any help is greatly appreciated.
Here is my MainActivity.java
public class MainActivity extends AppCompatActivity{
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "USE_YOUR_OWN_API_KEY";
static final String API_URL = "https://api.fullcontact.com/v2/person.json?";
static final String ClientId= "";
static final String ClientSecret = "";
static final String SCOPE = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new RetrieveFeedTask().execute();
Intent intent = new Intent(context, NavDrawerActivity.class);
startActivity(intent);
}
});
WifivsDataDialog myDiag = new WifivsDataDialog();
//myDiag.show(getFragmentManager(), "dialog_layout");
myDiag.setCancelable(false);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
new WifivsDataDialog().show(getFragmentManager(), "WiFi");
}
}
private int checkAvailableConnectionType() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
int type = activeNetwork.getType();
if(activeNetwork.isConnected() && (type == ConnectivityManager.TYPE_MOBILE ||
type == ConnectivityManager.TYPE_WIFI)) {
return type;
}
return -1;
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}
}
Here is my code that controls the app startup dialog.
public class WifivsDataDialog extends DialogFragment implements View.OnClickListener {
private CheckBox checkBox;
private Button button1;
private Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.dialog_box_layout, container);
checkBox = (CheckBox) mainView.findViewById(R.id.checkBox);
button1 = (Button) mainView.findViewById(R.id.button1);
button2 = (Button) mainView.findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// Store the isChecked to Preference here
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("DONT_SHOW_DIALOG", isChecked);
editor.commit();
}
});
return mainView;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// Do wifi stuff here
WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
dismiss();
break;
case R.id.button2:
// Do cellular stuff here
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
Boolean isConnected = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
if(isConnected == true)
{
dismiss();
}else
{
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Mobile Data is not turned on. Please turn Mobile Data on to continue.");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss();
Intent intentSettings = new Intent(Settings.ACTION_SETTINGS);
startActivity(intentSettings);
}
});
alertDialog.show();
}
break;
}
}
}
Here is my code settingsfragment.java
public class SettingsFragment extends Fragment
{
View myView;
Button button;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.settings_layout, container, false);
button= (Button)getActivity().findViewById(R.id.button3);
RadioGroup radioGroup = (RadioGroup) myView .findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
switch(checkedId) {
case R.id.radioButton7:
// switch to fragment 1
WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
Boolean isConnected = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
if(isConnected != true)
{
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Mobile Data is not turned on. Please turn Mobile Data on to continue.");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss();
Intent intentSettings = new Intent(Settings.ACTION_SETTINGS);
startActivity(intentSettings);
}
});
alertDialog.show();
}
break;
case R.id.radioButton6:
// Fragment 2
WifiManager wifiManager1 = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
wifiManager1.setWifiEnabled(true);
break;
}
}
public void onClick(View v) {
private void saveGenderInPreference () {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
RadioGroup radioGroup1 = (RadioGroup) getActivity().findViewById(R.id.radioGroup);
int selectedId = radioGroup1.getCheckedRadioButtonId();
if (selectedId == R.id.radioButton7)
editor.putBoolean("is_Wifi", true);
else
editor.putBoolean("is_Wifi", false);
editor.commit();
}
}
});
return myView;
}
}

Within one fragment 2 web services are being called

I have a MainActivity where the Swipeable Tabs are created and from there two fragments are called. I have 2 webservice for Fragment A and Fragment B where I have to parse data coming from server. I am using volley. When I am in the first fragment; both the webservice are being called and the data are not loaded for the first time. But in the Second time it is showing correctly but it should be like this that when I am in Fragment A the service of the Fragment A should be called and when I am in Fragment B the service of the Fragment B should be called. Please help me out. I am attaching the code snippets. I got stuck here.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
int status = 0 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*Setup the DrawerLayout and NavigationView
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
// Show menu icon
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
/**
* Lets inflate the very first fragment
* Here , we are inflating the NewsFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
// mNavigationView.setBackgroundColor(Color.parseColor("#CFCFCF"));
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
status = 1;
if (status == 1){
}
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sent){
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new VideosFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_draft) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new OpinionFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sports) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_weather) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about_us:
Intent intent = new Intent(MainActivity.this, AboutUs.class);
startActivity(intent);
return true;
case R.id.action_terms_of_use:
Intent intent_two = new Intent(MainActivity.this, TermsUse.class);
startActivity(intent_two);
return true;
case R.id.action_privacy_policy:
Intent intent_three = new Intent(MainActivity.this, PrivacyPolicy.class);
startActivity(intent_three);
return true;
case R.id.action_contact_us:
Intent intent_four = new Intent(MainActivity.this, ContactUs.class);
startActivity(intent_four);
case R.id.search:
// hidetext();
Toast.makeText(MainActivity.this, "In the development Phase... Thank You...", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// private void hidetext() {
//
// Intent i = new Intent(MainActivity.this, SearchResultActivity.class);
// startActivity(i);
// }
}
TopNewsFragment
public class TopNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/topnews";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
Movie movie;
private ListView listView;
private CustomListAdapter adapter;
String imageURL = "", title = "", description = "";
public static final String KEY_ID = "news_id";
public static final String KEY_HEADURL = "news_url";
public static final String KEY_DETAILS = "news_details";
public static final String KEY_TITLE = "news_title";
RequestQueue requestQueue;
public TopNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
intent.putExtra(KEY_ID, item.getNewsId());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0) {
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
title = movie.setTitle(homenews.getString("Title"));
description = movie.setDescription(homenews.getString("Description"));
movie.setDescription(homenews.getString("Description"));
imageURL = movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
// System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
LatestNewsFragment.java
public class LatestNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/latest";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
// contacts JSONArray
private JSONArray users = null;
RequestQueue requestQueue;
public static final String KEY_HEADURL="news_url";
public static final String KEY_DETAILS="news_details";
public static final String KEY_TITLE = "news_title";
public LatestNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
// intent.putExtra("URL", movie.getThumbnailUrl());
// intent.putExtra("title", movie.getTitle());
// intent.putExtra("description", movie.getDescription());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
// JsonObjectRequest jsonObjectRequest =
#Override
public void onResponse(JSONObject response) {
try {
hidePDialog();
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0){
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
movie.setDescription(homenews.getString("Description"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
What probably happens is that the two fragments are both loaded even though you are only looking at one fragment at a time. Instead of creating a new RequestQueue on every request you should only have one. For example create an Application class like so:
public class MyApp extends Application {
private RequestQueue mRequestQueue;
private static MyApp mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApp getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
}
Don't forget to add your application class to your manifest inside the activity tag:
<application
android:name=".MyApp"
Now you can put requests on that queue from your fragments:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Do something with error
}
});
//Put the actual request on the queue
MyApp.getInstance().addToRequestQueue(req);

java.lang.NullPointerException when resume activity in viewpager

I would like to resume activity which i have stored in share preferences in viewpager. I have stored the activity details in onSaveState and retrieve the activity getpreferences in onResume. But somehow, it returns error that the key is in null value in onSaveState. How to save the preferences in viewpager ?
Here is the code
public class FullScreenImageActivity extends AppCompatActivity {
ViewPager viewPager;
ImageView favBtn;
private SharedPreference sharedPreference;
Activity context = this;
private Fragment contentFragment;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_image); //TBS
FragmentManager fragmentManager = getSupportFragmentManager();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavouriteListFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavouriteListFragment.ARG_ITEM_ID) != null) {
contentFragment = fragmentManager
.findFragmentByTag(FavouriteListFragment.ARG_ITEM_ID);
}
}
}
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
String[] arr=i.getStringArrayExtra("array");
String url = i.getStringExtra("url");
sharedPreference = new SharedPreference();
viewPager = (ViewPager) findViewById(R.id.slider);
viewPager.setAdapter(new GalleryViewPagerAdapter(this, arr, position, url));
viewPager.setCurrentItem(position);
}
class GalleryViewPagerAdapter extends PagerAdapter {
private Context context;
LayoutInflater inflater;
private String[] imageArrayList;
private String mUrl;
private int mPosition;
private ProgressDialog mProgress;
public GalleryViewPagerAdapter(Context _context, String[] imageArrayList, int position, String url) {
context = _context;
this.imageArrayList = imageArrayList; //null;
this.mPosition=position;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mUrl=url;
}
#Override
public int getCount() {
return imageArrayList.length;
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
showProgress();
favBtn = (ImageView) findViewById(R.id.btn_favourite);
String favoriteUrl=sharedPreference.getPrefsFavUrl(context);
//Boolean stateBtnNow=sharedPreference.getBtnState(context,mUrl);//why mUrl change to same url with favourite
Boolean stateBtnNow=false;
if(stateBtnNow) {
favBtn.setColorFilter(Color.argb(255, 249, 0, 0));//red
}
else
{
favBtn.setColorFilter(Color.argb(255, 192, 192, 192));
}
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Boolean stateBtn = sharedPreference.getBtnState(context, mUrl);
Boolean stateBtn=false;
if (!stateBtn) {
sharedPreference.save(context, mUrl);
//edit to save url in array
//sharepreference.add(context, product);
sharedPreference.saveBtnState(context, stateBtn);
Toast.makeText(context,
"Added to Favourite!",
Toast.LENGTH_SHORT).show();
favBtn.setColorFilter(Color.argb(255, 249, 0, 0));//red
Toast.makeText(context,
"Button state is " + stateBtn,
Toast.LENGTH_SHORT).show();
} else {
sharedPreference.saveBtnState(context, stateBtn);
favBtn.setColorFilter(Color.argb(255, 192, 192, 192));//grey
}
}
});
View photoRow = inflater.inflate(R.layout.item_fullscreen_image, container,
false);
TouchImageView fullScreenImg;
fullScreenImg =(TouchImageView)photoRow.findViewById(R.id.img_flickr);
// added imageloader for better performance
StaggeredDemoApplication.getImageLoader().get(imageArrayList[position],
ImageLoader.getImageListener(fullScreenImg, R.drawable.bg_no_image, android.R.drawable.ic_dialog_alert), container.getWidth(), 0);
((ViewPager) container).addView(photoRow);
stopProgress();
return photoRow;
}
private void stopProgress() {
mProgress.cancel();
}
private void showProgress() {
mProgress = ProgressDialog.show(FullScreenImageActivity.this, "", "Loading...");
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("content", FavouriteListFragment.ARG_ITEM_ID);
super.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
}
}
Here is the code in sharepreferences
public class SharedPreference {
public static final String PREFS_NAME = "AOP_PREFS";
public static final String PREFS_STATE="AOP_BTN";
public static final String PREFS_FAV_URL="AOP_FAV_URL";
public static final String PREFS_KEY = "AOP_PREFS_String";
public static final String PREF_BTN_KEY = "AOP_PREF_BTN";
public static final String PREF_URL_KEY = "AOP_PREF_URL";
public SharedPreference() {
super();
}
public void save(Context context, String text) {
SharedPreferences settings;
Editor editor;
//edit here to add image array list
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putString(PREFS_KEY, text); //3
editor.commit(); //4
}
public String getValue(Context context) {
SharedPreferences settings;
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
text = settings.getString(PREFS_KEY, null);
return text;
}
public String getPrefsFavUrl(Context context){
SharedPreferences settings;
String favUrl;
settings = context.getSharedPreferences(PREFS_FAV_URL, Context.MODE_PRIVATE);
favUrl = settings.getString(PREF_URL_KEY, null);
return favUrl;
}
public void clearSharedPreference(Context context) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.clear();
editor.commit();
}
public void removeValue(Context context) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.remove(PREFS_KEY);
editor.commit();
}
public void saveBtnState(Context context, Boolean stateBtn) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putBoolean(PREF_BTN_KEY, stateBtn);//added state for button
editor.commit(); //4
}
public boolean getBtnState(Context context,String text)//edit to store url here and check the boolean here
{
SharedPreferences prefs;
prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String favUrl = getPrefsFavUrl(context);
boolean switchState = false;
if(favUrl.equals(text)) {
switchState=true;
}
return switchState;
}
public void saveFavourite(FragmentActivity activity, String favouriteUrl) {
SharedPreferences settings;
Editor editor;
settings = activity.getSharedPreferences(PREFS_FAV_URL, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putString(PREF_URL_KEY, favouriteUrl); //3
editor.commit(); //4
}
}
Here is the error log file
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.Class.newInstance()' on a null object reference
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at com.example.myapp.MainActivity.displayView(MainActivity.java:141)
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at com.example.myapp.MainActivity.onCreate(MainActivity.java:41)
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
Here is my MainActivity program
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentFlickrGridImage.OnFragmentInteractionListener, ShareActionProvider.OnShareTargetSelectedListener {
private int backstack_count;
private boolean viewIsAtHome;
private Fragment contentFragment;
private ShareActionProvider share;
private Intent shareIntent=new Intent(Intent.ACTION_SEND);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
displayView(R.id.recent_picture);
}
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.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener(this);
shareIntent.setType("text/plain");
}
private void replaceFragment(Fragment fragment, boolean isAddToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.flContent, fragment);
if (isAddToBackStack) {
transaction.addToBackStack(fragment.getClass().toString());
backstack_count ++;
}
transaction.commit();
}
#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);
MenuItem item = menu.findItem(R.id.share);
share = new ShareActionProvider(this);
MenuItemCompat.setActionProvider(item, share);
return(super.onCreateOptionsMenu(menu));
}
#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();
if (id == R.id.share) {
onShareAction();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onShareAction() {
String yourShareText = "test";
Intent shareIntent = ShareCompat.IntentBuilder.from(this).setType("text/plain").setText(yourShareText).getIntent();
// Set the share Intent
if (share != null) {
share.setShareIntent(shareIntent);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
displayView(item.getItemId());
return true;
}
private void displayView(int itemId) {
Fragment fragment = null;
Class fragmentClass = null;
String title="";
switch (itemId){
case R.id.one:
fragment = new FragmentFlickrGridImage("one");
title="one";
viewIsAtHome=true;
break;
case R.id.two:
fragment = new FragmentFlickrGridImage(" two");
title ="two";
viewIsAtHome=false;
break;
case R.id.three:
fragment = new FragmentFlickrGridImage("three");
title="three";
viewIsAtHome=false;
break;
case R.id.four:
fragment=new FavouriteListFragment();
title="Favourite";
viewIsAtHome=false;
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
getSupportActionBar().setTitle(title);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
if (!viewIsAtHome) { //if the current view is not the Recent Hot Girl fragment
displayView(R.id.recent_picture);
} else {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("Are you sure?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.setCancelable(false)
.setTitle("Exit");
builder.show();
}
}
#Override
public boolean onShareTargetSelected(ShareActionProvider source,
Intent intent) {
Toast.makeText(this, intent.getComponent().toString(),
Toast.LENGTH_LONG).show();
return(false);
}
}
The error line is:
fragment = (Fragment) fragmentClass.newInstance();
fragmentClass is always assigned with null object when you use it in fragmentClass.newInstance(), and it always have null value because you never assign it with other value. Try to remove these lines:
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Anyway, using non-empty constructor for the fragments is not a good practice. You should use this pattern instead.
EDIT
Check whether fragment is empty or not:
if (fragment != null){
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}

want to display an alert when internet connection is not available in android [duplicate]

This question already has answers here:
Android - Show a message if no internet connection and continue to check
(2 answers)
Closed 7 years ago.
I want to display an alert message when Internet connection is not available in my android project. My Activity class loads a list-view through Internet and if the devices doesn't have an Internet connection it simply displays the activity. I want to show a toast or a prompt that your device doesn't have Internet connection.
here is my activity class:
public class MainActivity2 extends AppCompatActivity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String TAG_TITLE = "title";
private static final String TAG_RATING = "rating";
private Toolbar mToolbar;
private FloatingActionButton fab;
// Movies json url
private static final String url = "http://groupdiscount.netne.net/android_connect/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity2.this, Register.class);
startActivity(intent);
}
});
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String rating = ((TextView) view.findViewById(R.id.rating))
.getText().toString();
// Starting single activity
Intent in = new Intent(getApplicationContext(),
SingleActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_RATING, rating);
startActivity(in);
}
});
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#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);
return true;
}
}
public boolean isOnline() {
boolean result;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()){
result=true;
}
else{
Toast.makeText(getBaseContext(), "Not Online",7000).show();
result=false;
}
return result;
}
and use it as following:
if(isOnline()){
loadListView(); // This would be the method that you load listview
}

Categories