How to update fragment/update fragment ui from activity? - android

Pageviewer.java code:
//hide status bar/action bar on single tap
package com.app.imageswiper;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Pageviwer extends AppCompatActivity {
private Integer[] mImageIds = {R.drawable.page001, R.drawable.page002,
R.drawable.page003};
private static final String DEBUG_TAG = "pageviwer ";
ImageView imageView;
float startXValue = 1;
public int num;
public int click;
protected static final String TAG = "Pageviwer";
private GestureDetector mGestureDetector;
public SharedPreferences prefs;
public static int Bookmark = 0;
public static int Pageno = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int Bookmark1 = prefs.getInt("Bookmark", 0);
Bookmark = Bookmark1;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int Pageno1 = prefs.getInt("Pageno", 0);
Pageno = Pageno1;
setContentView(R.layout.pageviwer);
imageView = (ImageView) findViewById(R.id.image_place_holder);
imageView.setImageResource(mImageIds[0]);
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
setupGestureDetector();
hideActionBar(); // hide action bar after 1 second
}
private void setupGestureDetector() {
mGestureDetector = new GestureDetector(this,
new GestureDetector.SimpleOnGestureListener() {
//Detecting Swipe/Fling Direction
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
Log.i(TAG, "onFling");
if (e1.getX() < e2.getX()) {
Log.d(TAG, "Left to Right swipe performed");
if (num == 2) {
num = num;
} else {
imageView.setImageResource(mImageIds[num + 1]);
num = num + 1;
}
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
}
if (e1.getX() > e2.getX()) {
Log.d(TAG, "Right to Left swipe performed");
if (num == 0) {
num = num;
} else {
imageView.setImageResource(mImageIds[num - 1]);
num = num - 1;
}
TextView tv1 = (TextView) findViewById(R.id.pageno);
tv1.setText("" + (num + 1));
Toast.makeText(getApplicationContext(), "value is " + num, Toast.LENGTH_LONG).show();
}
return true;
}
//detecting single tap
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.i(TAG, "onSingleTapUp");
Toast.makeText(getApplicationContext(), "Single Tap ", Toast.LENGTH_LONG).show();
//Remove notification bar and action bar
if (click == 0) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
if (getSupportActionBar() != null) getSupportActionBar().hide();
click = 1;
}
//Return notification bar and action bar
else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
if (getSupportActionBar() != null) getSupportActionBar().show();
click = 0;
}
return true;
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mGestureDetector != null) {
return mGestureDetector.onTouchEvent(event);
} else {
return super.onTouchEvent(event);
}
}
public void hideActionBar() {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// DO DELAYED STUFF
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
if (getSupportActionBar() != null) getSupportActionBar().hide();
click = 1;
}
}, 1000); // 1000 milliseconds (1 second)
}
#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();
if (id == com.app.imageswiper.R.id.action_settings) {
Bookmark=1;
prefs.edit().putInt("Bookmark", Bookmark).commit();
prefs.edit().putInt("Pageno", num).commit();
Toast.makeText(getApplicationContext(), "Bookmark value is "+Bookmark, Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
ViewPagerAdapter code:
package com.app.imageswiper;
/**
* Created by Jaffer on 14-Apr-16.
*/
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class Bookmarks extends Fragment {
public SharedPreferences prefs;
public static int Bookmark = 0;
public static int Pageno = 0;
Button sendButton = null;
View inflatedView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int Bookmark1 = prefs.getInt("Bookmark", 0);
Bookmark = Bookmark1;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int Pageno1 = prefs.getInt("Pageno", 0);
Pageno = Pageno1;
this.inflatedView = inflater.inflate(R.layout.bookmarks, container, false);
sendButton = (Button) inflatedView.findViewById(R.id.bookmark);
if(Bookmark==1){sendButton.setText("Page "+Pageno);}
else {sendButton.setText("No Bookmark ");}
if(sendButton == null)
{
Log.d("debugCheck", "HeadFrag: sendButton is null");
return inflatedView;
}
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Pageviwer.class);
startActivity(intent);
}
});
return inflatedView;
}
}
bookmarks.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/bookmarks">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/bookmark"
android:layout_alignParentBottom="true" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
</LinearLayout>
I don't know how to update the button text from Pageviewer.java for the button with R.id.bookmark that shows up on the Bookmarks fragment on the click of menu item R.id.action_settings. I want to do this so that the button text corresponds to the page that is being bookmarked. I tried alot of things but to no avail. Can someone please help me with anything?
Thanks in advance

Create a method in your fragment to update the text of your button.
public void updateText(String newText){
//assuming button is globally declared in your fragment.
button.setText(newText);
}
Instead of Gesture Detector you could use a ViewPager which supports swiping to the left and right.You can find a sample implementation here.
Then in your Activty,implement PageChanegListener on ViewPager.
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.You have to implement viewpager's adapter with getItem(index) which returns a fragment at that index.
BookMarkFragment fragment (BookMarkFragment)mAdapter.getItem(position);
fragment.updateText(newText);
};
});

You should save the state of a button somewhere. Your field int Bookmark == 0, so expression sendButton.setText("Page "+Pageno); never execute. Save the state in SharedPreferences and get this state. Like this:
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
int isBookmark = prefs.getInt("Bookmark", 0);
int mPageno = prefs.getInt("Pageno", 0);
...
if(isBookmark == 1){
sendButton.setText("Page " + mPageno);
} else {
sendButton.setText("No Bookmark");
}

Related

Bug in app while rotating Android phone

hello guys i started to learn to build android applications via udacy. After a long troubleshooting i didnt find something that can cause the bug that i have. the bug is that when i rotate the phone the view seems to clone it self and not deleting the previous one if someone can help me ill be very happy.
1) normal state of app:
2) after rotation:
3) and after another rotation the application crashing
it never happend until i added the code in the xml file of the view:
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for weather forecast list item for future day (not today) -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/list_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/list_item_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tomorrow"/>
<TextView
android:id="#+id/list_item_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:gravity="right">
<TextView
android:id="#+id/list_item_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="81"
android:paddingLeft="10dp"/>
<TextView
android:id="#+id/list_item_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="68"
android:paddingLeft="10dp"/>
</LinearLayout>
</LinearLayout>
Activity Code:
package com.example.andy.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private String FORECASTFRAGMENT_TAG = "FFTAG";
String mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new MainActivityFragment(), FORECASTFRAGMENT_TAG)
.commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mLocation = Utility.getPreferredLocation(this);
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();
}
});
}
#Override
protected void onResume() {
super.onResume();
String location = Utility.getPreferredLocation(this);
if(location != null && location != mLocation){
MainActivityFragment ff = (MainActivityFragment)getSupportFragmentManager().findFragmentById(R.id.fragment);
if(ff != null){
ff.onLocationChanged();
}
mLocation = location;
}
}
#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) {
// 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){
Intent settings = new Intent(this,SettingsActivity.class);
startActivity(settings);
}
if(R.id.action_map == id){
openPreferedLocationMap();
}
return super.onOptionsItemSelected(item);
}
private void openPreferedLocationMap(){
String location = Utility.getPreferredLocation(this);
Uri geoLocation = Uri.parse("geo:0,0?").buildUpon().appendQueryParameter("q",location).build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if(intent.resolveActivity(getPackageManager()) != null){
startActivity(intent);
}
else{
Log.d("SHOWING MAP PROBLEMM","could't call"+ location+ "intent");
}
}
}
Fragment Code:
package com.example.andy.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.andy.sunshine.app.data.WeatherContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int FORECAST_LOADER = 0;
// For the forecast view we're showing only a small subset of the stored data.
// Specify the columns we need.
private static final String[] FORECAST_COLUMNS = {
// In this case the id needs to be fully qualified with a table name, since
// the content provider joins the location & weather tables in the background
// (both have an _id column)
// On the one hand, that's annoying. On the other, you can search the weather table
// using the location set by the user, which is only in the Location table.
// So the convenience is worth it.
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATE,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.LocationEntry.COLUMN_COORD_LAT,
WeatherContract.LocationEntry.COLUMN_COORD_LONG
};
// These indices are tied to FORECAST_COLUMNS. If FORECAST_COLUMNS changes, these
// must change.
static final int COL_WEATHER_ID = 0;
static final int COL_WEATHER_DATE = 1;
static final int COL_WEATHER_DESC = 2;
static final int COL_WEATHER_MAX_TEMP = 3;
static final int COL_WEATHER_MIN_TEMP = 4;
static final int COL_LOCATION_SETTING = 5;
static final int COL_WEATHER_CONDITION_ID = 6;
static final int COL_COORD_LAT = 7;
static final int COL_COORD_LONG = 8;
private ForecastAdapter mForecastAdapter;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, 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.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// The CursorAdapter will take data from our cursor and populate the ListView.
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, cursor.getLong(COL_WEATHER_DATE)
));
startActivity(intent);
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(FORECAST_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
private void updateWeather() {
FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity());
String location = Utility.getPreferredLocation(getActivity());
weatherTask.execute(location);
}
public void onLocationChanged(){
updateWeather();
getLoaderManager().restartLoader(FORECAST_LOADER,null,this);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String locationSetting = Utility.getPreferredLocation(getActivity());
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
locationSetting, System.currentTimeMillis());
return new CursorLoader(getActivity(),
weatherForLocationUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mForecastAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mForecastAdapter.swapCursor(null);
}
}
And Class That Extends CursorAdapter "ForecastAdapter":
package com.example.andy.sunshine.app;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.andy.sunshine.app.data.WeatherContract;
/**
* {#link ForecastAdapter} exposes a list of weather forecasts
* from a {#link android.database.Cursor} to a {#link android.widget.ListView}.
*/
public class ForecastAdapter extends CursorAdapter {
private final int VIEW_TYPE_TODAY = 0;
private final int VIEW_TYPE_FUTURE_DAY = 1;
public ForecastAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public int getItemViewType(int position) {
return (position == 0)? VIEW_TYPE_TODAY:VIEW_TYPE_FUTURE_DAY;
}
#Override
public int getViewTypeCount() {
return 2;
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(Context context,double high, double low) {
boolean isMetric = Utility.isMetric(mContext);
String highLowStr = Utility.formatTemperature(context,high, isMetric) + "/" + Utility.formatTemperature(context,low, isMetric);
return highLowStr;
}
/*
This is ported from FetchWeatherTask --- but now we go straight from the cursor to the
string.
*/
private String convertCursorRowToUXFormat(Context context,Cursor cursor) {
// get row indices for our cursor
String highAndLow = formatHighLows(context,
cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP),
cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP));
return Utility.formatDate(cursor.getLong(MainActivityFragment.COL_WEATHER_DATE)) +
" - " + cursor.getString(MainActivityFragment.COL_WEATHER_DESC) +
" - " + highAndLow;
}
/*
Remember that these views are reused as needed.
*/
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int VIEW_TYPE = getItemViewType(cursor.getPosition());
int layoutId = -1;
if(VIEW_TYPE == VIEW_TYPE_TODAY){
layoutId = R.layout.list_item_forecast_today;
}else if(VIEW_TYPE == VIEW_TYPE_FUTURE_DAY){
layoutId = R.layout.list_item_forecast;
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
view.setTag(viewHolder);
return view;
}
/*
This is where we fill-in the views with the contents of the cursor.
*/
#Override
public void bindView(View view, Context context, Cursor cursor) {
// our view is pretty simple here --- just a text view
// we'll keep the UI functional with a simple (and slow!) binding.
MyViewHolder viewHolder = (MyViewHolder)view.getTag();
viewHolder.iconView.setImageResource(R.mipmap.ic_launcher);
// TODO Read date from cursor
long dateInMillis = cursor.getLong(MainActivityFragment.COL_WEATHER_DATE);
viewHolder.dateView.setText(Utility.getFriendlyDayString(context, dateInMillis));
// TODO Read weather forecast from cursor
viewHolder.descriptionView.setText(cursor.getString(MainActivityFragment.COL_WEATHER_DESC));
// Read user preference for metric or imperial temperature units
boolean isMetric = Utility.isMetric(context);
// Read high temperature from cursor
double high = cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP);
viewHolder.highTempView.setText(Utility.formatTemperature(context,high, isMetric));
// TODO Read low temperature from cursor
double low = cursor.getDouble(MainActivityFragment.COL_WEATHER_MIN_TEMP);
viewHolder.lowTempView.setText(Utility.formatTemperature(context,low, isMetric));
}
public static class MyViewHolder {
public final ImageView iconView;
public final TextView dateView;
public final TextView descriptionView;
public final TextView highTempView;
public final TextView lowTempView;
public MyViewHolder(View view){
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
dateView = (TextView)view.findViewById(R.id.list_item_date_textview);
descriptionView = (TextView)view.findViewById(R.id.list_item_forecast_textview);
highTempView = (TextView)view.findViewById(R.id.list_item_high_textview);
lowTempView = (TextView)view.findViewById(R.id.list_item_low_textview);
}
}
}
if you want to see the whole project and check maybe for errors that may cause that i posting here my github https://github.com/obruchkov/Sunshine with all the code that i did. please help me guys

cannot able to fetch Boolean value from the shared Preference

I have a checkbox , I want it to be unchecked by default. i.e False.
On manually checking the checkbox, i.e if the checkbox is checked , it perform certain action in another class.
I tried to save the sate of the checkbox using SharedPreference, but when I tried to fetch the checkbox value in another class using GetBoolean , I am not getting the saved value.
my layout xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number of Circle" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
<CheckBox
android:id="#+id/chkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/enable_touch_checkBox"
/>
<Button
android:id="#+id/buttonAlert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="131dp"
android:text="save"
/>
</LinearLayout>
MyPreferenceActivity class
package de.vogella.android.wallpaper;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
public class MyPreferencesActivity extends Activity {
private PrefManager pref;
private TextView txtGoogleUsername, txtNoOfCircles, txtGalleryName;
private CheckBox checkBox ;
private Button btnSave;
private Boolean checkBoxValue;
private static final String PREF_NAME = "wallpaper";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
txtNoOfCircles = (TextView) findViewById(R.id.editText1);
checkBox = (CheckBox) findViewById(R.id.chkBox1);
btnSave = (Button) findViewById(R.id.buttonAlert);
pref = new PrefManager(getApplicationContext());
txtNoOfCircles.setText(String.valueOf(pref.getNoOfGridCircles()));
//checkBox.setChecked(pref.getCheckBox());
/********************************/
SharedPreferences sharedPreferences =PreferenceManager.getDefaultSharedPreferences(this);
checkBoxValue = sharedPreferences.getBoolean("Box", false);
if(checkBoxValue){
checkBox.setChecked(true);
}
else
{
checkBox.setChecked(false);
}
/********************************/
/*saveLogin = pref.getCheckBox();
if(saveLogin == true){
checkBox.setChecked(true);
}*/
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//savePreferences("Box", checkBox.isChecked());
if(checkBox.isChecked())
{
//pref.setCheckBox(true);
savePreferences("Box", checkBox.isChecked());
Toast.makeText(getApplicationContext(),
"hii",
Toast.LENGTH_LONG).show();
}
else
{
savePreferences("Box", checkBox.isChecked());
//pref.setCheckBox(false);
}
boolean vals = pref.getCheckBox();
//checkBox = (CheckBox) findViewById(R.id.chkBox1);
String no_of_columns = txtNoOfCircles.getText().toString()
.trim();
//checkBox.get
if (no_of_columns.length() == 0 || !isInteger(no_of_columns)) {
Toast.makeText(getApplicationContext(),
getString(R.string.toast_enter_valid_number),
Toast.LENGTH_LONG).show();
return;
}
if(no_of_columns != null || no_of_columns.equals(" ") )
{
if (!no_of_columns.equalsIgnoreCase(String.valueOf(pref
.getNoOfGridCircles()))) {
// User changed the settings
// save the changes and launch SplashScreen to initialize
// the app again
// pref.setGoogleUsername(googleUsername);
pref.setNoOfGridCircles(Integer.parseInt(no_of_columns));
// pref.setCheckBox(val);
// pref.setGalleryName(galleryName);
// start the app from SplashScreen
Intent i = new Intent(MyPreferencesActivity.this,
SetWallpaperActivity2.class);
// Clear all the previous activities
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
} else {
// user not modified any values in the form
// skip saving to shared preferences
// just go back to previous activity
onBackPressed();
}
}
}
});
}
public boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (Exception e) {
return false;
}
}
private void savePreferences(String key, boolean value){
//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME,0);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
}
My wallpaperService class
package de.vogella.android.wallpaper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.animation.AnimatorSet.Builder;
import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.service.wallpaper.WallpaperService;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MyWallpaperService extends WallpaperService {
private final String TAG = getClass().getSimpleName();
private static final String PREF_NAME = "wallpaper";
//private PrefManager pref = new PrefManager(getApplicationContext());
#Override
public Engine onCreateEngine() {
Log.i( TAG, "onCreateEngine" );
return new MyWallpaperEngine();
}
private class MyWallpaperEngine<YourActivity> extends Engine {
private final Handler handler = new Handler();
private final Runnable drawRunner = new Runnable() {
#Override
public void run() {
draw();
}
};
private List<MyPoint> circles;
private Paint paint = new Paint();
Bitmap image = null;
private int width;
int height;
private boolean visible = true;
private int maxNumber;
private int maxNumber2;
private boolean touchEnabled;
private boolean touchEnabled2;
SharedPreferences prefs = null;
int fatchDataSize = 10;
ProdAdDetails []prodobj = new ProdAdDetails[fatchDataSize];
HashMap<Integer,String> map = new HashMap<Integer,String>();
Canvas canvas = null;
public MyWallpaperEngine()
{
pref= new PrefManager(getApplicationContext());
//prefs=PreferenceManager.getDefaultSharedPreferences(MyWallpaperService.this);
prefs = getSharedPreferences(PREF_NAME,0);
touchEnabled = prefs.getBoolean("Box",false);
}
#Override
public void onVisibilityChanged(boolean visible) {
this.visible = visible;
if (visible) {
handler.post(drawRunner);
} else {
handler.removeCallbacks(drawRunner);
}
}
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
this.visible = true;
handler.removeCallbacks(drawRunner);
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
this.width = width;
this.height = height;
super.onSurfaceChanged(holder, format, width, height);
}
#Override
public void onTouchEvent(MotionEvent event) {
if (touchEnabled) {
if (event.getAction() == MotionEvent.ACTION_MOVE )
{
Toast.makeText(getApplicationContext(), "Move", Toast.LENGTH_SHORT).show();
}
else
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
Toast.makeText(getApplicationContext(), "Down", Toast.LENGTH_SHORT).show();
}
super.onTouchEvent(event);
} // if block end
}
private void draw() {
SurfaceHolder holder = getSurfaceHolder();
//Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
if (circles.size() >= maxNumber2) {
circles.clear();
map = new HashMap<Integer,String>();
}
int x = (int) (width * Math.random());
int y = (int) (height * Math.random());
circles.add(new MyPoint(null, String.valueOf(circles.size() + 1), x, y));
drawCircles(canvas, circles);
}
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
handler.removeCallbacks(drawRunner);
if (visible) {
handler.postDelayed(drawRunner, 10000);
}
}
// Surface view requires that all elements are drawn completely
private void drawCircles(Canvas canvas, List<MyPoint> circles) {
canvas.drawColor(Color.LTGRAY);
int i=0;
for (MyPoint point : circles) {
//-------------------------------
paint.setTextSize(20);
paint.setStrikeThruText(true);
image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(image, point.x, point.y, null);
//touchEnabled = ((SharedPreferences) paint).getBoolean("touch", true);
//=====================================
ProdAdDetails pad = prodobj[i];//(ProdAdDetails)point.prodobj;
String prodName = pad.getProd_name();
String prodDtl = pad.getProd_details();
String prodCompName = pad.getProd_comp_name();
String prodPrice = pad.getProd_price();
final String prodDtls = prodDtl+"\nCompany :"+prodCompName+"\nRate :"+prodPrice+"%";
canvas.drawText(prodName, point.x+1, point.y+1, paint);
canvas.drawBitmap(image, point.x, point.y, null);
int key = point.x;
System.out.println("put:::"+key);
map.put(key, prodDtls);
//-------------------------------
//canvas.drawPaint(paint);
//Circle(point.x, point.y, 40.0f, paint);
//Toast.makeText(getApplicationContext(), prodDtls, Toast.LENGTH_SHORT).show();
i++;
}
}
}
}
I have posted my code, any suggestion or advice will be of grate helpfull, as I am not able to understand where I am going wrong.
public static String KEY="Box";
private void savePreferences(boolean value){
SharedPreferences sharedpreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY,value);
editor.commit();
}
Retrieving End
SharedPreferences getpreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
boolean isChecked=getpreferences.getBoolean("Box",false);

Two activities sending data to each other

Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#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_detais_rest, 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.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#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_quentity, 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);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);

ListActivity onScroll never fired

I have a ListActivity that implements OnScrollListener. Unfortunality the methods onScroll and onScrollStateChanged are never fired.
I have absolutly no idear why. The data is shown correctly. I am able to scroll inside my view... Do you see the problem?
package bc.qz.client.android.activity;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import bc.qz.client.android.R;
import bc.qz.client.android.adapter.ScoreListAdapter;
import bc.qz.client.android.proxy.RemoteServletCaller;
import de.bc.qz.business.Score;
public class ScoreActivity extends ListActivity implements OnScrollListener{
private SharedPreferences mSharedPreferences;
private RemoteServletCaller mRemoteServletCaller;
private Runnable lViewScoreRunnable;
private String mUuid;
private String mUsername;
private ProgressDialog mProgressDialog = null;
private ScoreListAdapter mScoreListAdapter;
List<Score> mAllScore = new ArrayList<Score>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mRemoteServletCaller = new RemoteServletCaller();
mSharedPreferences = this.getSharedPreferences(
"de.bc.qz.client.sharedpreferences", Context.MODE_PRIVATE);
mUuid = mSharedPreferences.getString("uuid", null);
mUsername = mSharedPreferences.getString("user", null);
mScoreListAdapter = new ScoreListAdapter(this, mAllScore);
setListAdapter(mScoreListAdapter);
lViewScoreRunnable = new Runnable() {
#Override
public void run() {
loadAllScore(mUsername, mUuid);
}
};
Thread thread = new Thread(null, lViewScoreRunnable,
"MagentoBackground");
thread.start();
mProgressDialog = ProgressDialog.show(ScoreActivity.this,
"Bitte warten...", "Lade Highscore...", true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_score_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.goToTop:
return true;
case R.id.goToBottom:
return true;
case R.id.goToMine:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
System.out.println("onScroll");
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
System.out.println("onScrollStateChanged");
}
private void loadAllScore(String pUsername, String pUuid) {
try {
if (null == mUuid || mUsername == null) {
mUuid = UUID.randomUUID().toString();
mSharedPreferences.edit().putString("uuid", mUuid).commit();
mAllScore.addAll(mRemoteServletCaller.getAllScore(1, 50));
} else {
mAllScore.addAll(mRemoteServletCaller.getAllScore(mUsername,
mUuid));
}
} catch (Exception e) {
return;
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if (mAllScore != null && mAllScore.size() > 0) {
mScoreListAdapter.notifyDataSetChanged();
for (int i = 0, N = mAllScore.size(); i < N; i++)
mScoreListAdapter.add(mAllScore.get(i));
}
mProgressDialog.dismiss();
}
};
}
getListView().setOnScrollListener(this);

Sensor Reading keeps increasing even after closing app, Android

I have make this app which calculates Linear Acceleration of device of all dimension, combines it, and calculates net acceleration. Top five acceleration values are stored in Shared Preference key-value pairs.
The problem is when I close the app and reopen it, I find the values increased to a much higher level. I don't seem to catch the point in the code from where it is happening.
Please Help me out.
ShakoMeter.java (this is my main activity where all sensor data is collected and stored)
package com.example.shake_o_meter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ShakeOMeter extends Activity implements SensorEventListener{
float ro(double ax2) {
DecimalFormat df = new DecimalFormat("#.###");
return Float.valueOf(df.format(ax2));
}
SensorManager smngr;
Sensor sen;
TextView t,t3;
double max=-1;
double ax = 0,ay = 0,az = 0;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
ArrayList<Float> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shake_ometer);
t = (TextView)findViewById(R.id.TextView1);
// Showing initial message
TextView textview = new TextView(getApplicationContext());
textview.setText("Get ready to Shake It!!");
textview.setBackgroundColor(Color.BLACK);
textview.setTextColor(Color.WHITE);
textview.setTextSize(30);
textview.setPadding(10,10,10,10);
textview.setGravity(Gravity.CENTER_VERTICAL);
Toast toast = new Toast(getApplicationContext());
toast.setView(textview);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.FILL, 0, 0);
toast.show();
//Getting Sensor Control
smngr = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sen = (Sensor) smngr.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
//Obtaining SharedPreferance for storing key-value pairs of high scores.
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPref.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shake_ometer, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
list = new ArrayList<Float>();
ax = event.values[0];
ay = event.values[1];
az = event.values[2];
double temp=Math.sqrt(ro(ax)*ro(ax)+ro(ay)*ro(ay)+ro(az)*ro(az));
if(temp>=max){
max=temp;
t.setText(ro(max)+"");
list.add(sharedPref.getFloat("1", 0));
list.add(sharedPref.getFloat("2", 0));
list.add(sharedPref.getFloat("3", 0));
list.add(sharedPref.getFloat("4", 0));
list.add(sharedPref.getFloat("5", 0));
if(max>list.get(0)){
list.remove(0);
list.add((float) max);
Collections.sort(list);
editor.putFloat("1", list.get(0));
editor.putFloat("2", list.get(1));
editor.putFloat("3", list.get(2));
editor.putFloat("4", list.get(3));
editor.putFloat("5", list.get(4));
editor.commit();
System.out.println(sharedPref.getFloat("5", 0)+" "
+sharedPref.getFloat("4", 0)+" "
+sharedPref.getFloat("3", 0)+" "
+sharedPref.getFloat("2", 0)+" "
+sharedPref.getFloat("1", 0));
}
}
}
public void onClickReset(View view){
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void onClickTopFive(View view){
Intent intent = new Intent(getApplicationContext(),TopFive.class);
startActivity(intent);
}
#Override
protected void onResume(){
super.onResume();
final ShakeOMeter sh = this;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
smngr.registerListener(sh, sen, SensorManager.SENSOR_DELAY_NORMAL);
}
},3000);
}
#Override
protected void onPause() {
super.onPause();
smngr.unregisterListener(this);
}
protected void onStop(){
super.onStop();
smngr.unregisterListener(this);
}
public void onDestroy(){
super.onDestroy();
smngr.unregisterListener(this);
finish();
}
}
TopFive.java (This is a sub Activity where top five activities are displayed)
package com.example.shake_o_meter;
import java.text.DecimalFormat;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class TopFive extends Activity {
float ro(double ax2) {
DecimalFormat df = new DecimalFormat("#.###");
return Float.valueOf(df.format(ax2));
}
SharedPreferences sharedPref;
SharedPreferences.Editor edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_five);
// Show the Up button in the action bar.
setupActionBar();
TextView t1 = (TextView) findViewById(R.id.T1);
TextView t2 = (TextView) findViewById(R.id.T2);
TextView t3 = (TextView) findViewById(R.id.T3);
TextView t4 = (TextView) findViewById(R.id.T4);
TextView t5 = (TextView) findViewById(R.id.T5);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
edit = sharedPref.edit();
t1.setText(ro(sharedPref.getFloat("1", 0))+"");
t2.setText(ro(sharedPref.getFloat("2", 0))+"");
t3.setText(ro(sharedPref.getFloat("3", 0))+"");
t4.setText(ro(sharedPref.getFloat("4", 0))+"");
t5.setText(ro(sharedPref.getFloat("5", 0))+"");
}
public void onClickReset(View view){
edit.putFloat("1", 0);edit.commit();
edit.putFloat("2", 0);edit.commit();
edit.putFloat("3", 0);edit.commit();
edit.putFloat("4", 0);edit.commit();
edit.putFloat("5", 0);edit.commit();
Intent intent = getIntent();
finish();
startActivity(intent);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.top_five, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories

Resources