Asynctask for update button - java

How to update my UI button for disabled button on/off if i have condition. The condition : if i get value = 1.0 the button power on is disabled & and if i get value 0 the button power off disabled. I want the button always show up the new value.
This is my code :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_controller, container, false);
mSwitchStatus = (TextView) rootView.findViewById(R.id.statusSwitch);
ImageButton On = (ImageButton)rootView.findViewById(R.id.on);
ImageButton Off = (ImageButton)rootView.findViewById(R.id.off);
callAsynchronousTask();
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplication(), "ON", Toast.LENGTH_SHORT).show();
SendApi sendApi = new SendApi();
sendApi.execute();
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplication(), "OFF", Toast.LENGTH_SHORT).show();
SendApi sendApi = new SendApi();
sendApi.execute();
}
});
// Inflate the layout for this fragment
return rootView;
}
Repeat AsyncTask
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
GetApi getApi = new GetApi();
getApi.execute();
} catch (Exception e) {
android.util.Log.i("Error", "Error");
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 100);
}
AsyncTask for GETApi
public class GetApi extends AsyncTask<Object, Object, Value[]> {
private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
private final String SWITCHID = "xxxxxxxxxxxxxxxxxxxxxxxxx";
private ImageButton On,Off ;
#Override
protected Value[] doInBackground(Object... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable statusSwitch = apiClient.getVariable(SWITCHID);
Value[] variableValues = statusSwitch.getValues();
return variableValues;
}
#Override
protected void onPostExecute(Value[] variableValues) {
String status = Double.toString(variableValues[0].getValue());
mSwitchStatus.setText(status);
if(status.equals("1.0")){
On.setVisibility(View.INVISIBLE);
}
}
}
Fragment_controller.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#1d4851"
tools:context=".activity.ControllerFragment">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/off"
android:src="#drawable/ic_off"
android:background="#null"
android:layout_marginTop="79dp"
android:layout_below="#+id/textView2"
android:layout_alignLeft="#+id/on"
android:layout_alignStart="#+id/on"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/on"
android:background="#null"
android:src="#drawable/ic_on"
android:layout_marginTop="87dp"
android:layout_alignTop="#+id/off"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Water Pump Controller "
android:id="#+id/textView2"
android:textColor="#ffffff"
android:textSize="20dp"
android:layout_marginTop="19dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" "
android:id="#+id/statusSwitch"
android:textColor="#ffffff"
android:textSize="20dp"
android:layout_marginTop="250dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>

you have initialize your button in onCreateView like
ImageButton On = (ImageButton)rootView.findViewById(R.id.on);
and trying to access it in onPostExecute().they aren't global.
And to disable you have to call setEnable(false) not setVisibility
And you can also send it as Rathna Kumaran said.
public class GetApi extends AsyncTask<Object, Object, Value[]> {
private Button button;
public GetApi(Button mButton){
this.button = button;
}
private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
private final String SWITCHID = "xxxxxxxxxxxxxxxxxxxxxxxxx";
#Override
protected Value[] doInBackground(Object... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable statusSwitch = apiClient.getVariable(SWITCHID);
Value[] variableValues = statusSwitch.getValues();
return variableValues;
}
#Override
protected void onPostExecute(Value[] variableValues) {
String status = Double.toString(variableValues[0].getValue());
mSwitchStatus.setText(status);
if(status.equals("1.0")){
button.setVisibility(View.INVISIBLE);
}
}
}

1.Create a constructor in a AsyncTask and send the button as parameter. ex. getApi(buttonOne).execute();
Inside a getApi() constructor declare a local variable "Button" and assigned to that.
In onPostExecute() -> buttonOne.setVisibility(View.INVISIBLE).
In asyncTask , "onPostExecute()" will perform in a main thread. UI elements should only get update in a main thread. So that passing a UI element into an Asynctask and it can be update inside the onPostExecute.

Related

How i can fix AsyncTask error with TextView [duplicate]

This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 3 years ago.
I want to display a timer from 1 to 100 in my TextView, but this throws me an Exception. My application throws a RuntimeException like shown below:
Thanks in advance for your help.
java.lang.RuntimeException: An error occurred while executing
doInBackground()
My MainActivity class where the RuntimeException is thrown.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new QQ().execute();
}
});
}
public void onProgressUpdate(int i) {
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
txt.setText(i);
}
private class QQ extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Integer doInBackground(Integer... args) {
for (int i = 0; i < 1000000; i++) {
try {
Thread.sleep(1000); ///задержка
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
return null;
}
return null;
}
private void publishProgress(int i) {
publishProgressq(i);
}
protected void onPostExecute(int i) {
}
}
private void publishProgressq(int i) {
onProgressUpdate(i);
}
}
My Layout class in xml
<?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:background="#bbbbbb"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bbbbbb"
android:gravity="top"
android:orientation="horizontal">
<TextView
android:id="#+id/txt"
android:layout_width="151dp"
android:layout_height="110dp"
android:textSize="45dp"
android:text="0">
</TextView>
<Button
android:id="#+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="START" />
<Button
android:id="#+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="STOP" />
</LinearLayout>
</LinearLayout>
You can change your code as below:
public void onProgressUpdate(int i) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
txt.setText(i);
}
});
}
It will run on main thread.
Inside your public void onProgressUpdate , set text like this :
txt.setText(String.valueOf(i));
If you set a TextView to an int, it will be interpreted as an Android resource id. If you want the value of the int as your text (and not the resource it points to), make it a String first.

DataBinding not Updating TextView when notifyPropertyChanged(BR.xx) is used

I have a working dataBinding for the functions being called from XML (ie."#{user.mUCL}"). But When i use notifyPropertyChanged(BR.mUCL) in any method or anywhere New values dont get updated, I have provided a sample issue below, where for-loop updated Text1 with values, but other Text2 fails to update with the same values "not-worked".
JavaFragment
public class FragmentTwo extends Fragment {
Update_observable updateObservable;
TextView fragment_quote_open_val;
public FragmentTwo() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Fragment2Binding fragmentTwoBinding = DataBindingUtil.inflate(inflater,R.layout.fragment2,null,false);
View view = fragmentTwoBinding.getRoot();
updateObservable = new Update_observable();
fragmentTwoBinding.setUser(updateObservable);
fragment_quote_open_val=(TextView)view.findViewById(R.id.fragment_quote_open_val);
bindingLoop();
return view;
}
#BindingAdapter({"mUCL"})
public static void runMe(TextView view, String message) {
if (message != null)
view.setText(message);
}
public void bindingLoop(){
final int[] k = {0};
final Update_observable ss=new Update_observable();
final Handler handler = new Handler();
final int delay = 3000; //milliseconds
handler.postDelayed(new Runnable(){
public void run(){
//do something
k[0]++;
fragment_quote_open_val.setText(String.valueOf(k[0]));
ss.setmUCL(String.valueOf(k[0]));
handler.postDelayed(this, delay);
}
}, delay);
}
}
BaseObservable
public class Update_observable extends BaseObservable {
public String mUCL= "not-worked";
#Bindable
public String getmUCL() {
return this.mUCL;
}
public void setmUCL(String mUCL) {
this.mUCL = mUCL;
notifyPropertyChanged(BR.mUCL);
}
}
XML
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="user"
type="com.journaldev.androidmvvmbasics.fragments.Update_observable"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff04"
android:orientation="vertical"
android:gravity="center"
tools:context="com.journaldev.androidmvvmbasics.fragments.FragmentTwo">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/fragment_quote_open_val"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:textColor="#000000"
android:textSize="16dp" />
<TextView
android:id="#+id/fragment_quote_ucl_val"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{user.mUCL}"
android:layout_margin="20dp"
bind:mUCL="#{user.mUCL}"
android:textColor="#000000"
android:textSize="16dp" />
</LinearLayout>
</layout>
kindly make sure you do DataBindingUtil.inflate in Base class.
Fragment1Binding fragmentOneBinding = DataBindingUtil.inflate(inflater,R.layout.fragment1,null,false);
View view = fragmentOneBinding.getRoot();
fragmentOneBinding.setUsermodel(new UserModel("XXXX","XXXX"));
or
ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this,
R.layout.activity_main);
activityMainBinding.setUser(new User());
activityMainBinding.executePendingBindings();
then in BaseObservable class do
#Bindable
public String mEmail= "....";
rebuild project, just to make sure #Bindable is done for sure
now call, as per your requirement.
notifyPropertyChanged(BR.xxx);

NullPointerException when trying to open ZXingScannerView

I'm new to Android development so please bear with me.
I have the code inside an activity that implements qr scanning. Basically there is an activity before this segments of codes, but its just clicking of a button to go here. and whenever I do that, my app crashes and that is the error that returns. The idea of the app is once the user click the button, it will first display a qr scanner, once it has been scanned, it will now call this XML File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/scanbg"
tools:context=".ScanActivity">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="62dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question Here"
android:textSize="22dp"
android:id="#+id/questionhere"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/questionhere"
android:hint="Answer"
android:id="#+id/answerhere"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct or not indicator"
android:id="#+id/indicator"
android:layout_below="#id/answerhere"
android:textSize="18dp"/>
<!--this textview will be programmed to be changed as correct or not-->
<!--if answer == correct then "correct!" else "wrong answer"-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Point(s):"
android:id="#+id/userpoints"
android:layout_below="#id/indicator"
android:textSize="18dp"/>
<Button
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/userpoints"
android:layout_alignParentEnd="true"
android:text="Go"
android:textSize="14dp"
android:background="#B0DAD5"
android:id="#+id/gosagot"/>
</RelativeLayout>
and Here is the java file
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Button validateanswer;
ProgressDialog progress;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
validateanswer = (Button)findViewById(R.id.gosagot); //Im having error here
validateanswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
EditText theanswer = (EditText)findViewById(R.id.answerhere);
String sagotdito = theanswer.getText().toString();
RequestFactory.confirmanswer(ScanActivity.this, sagotdito, new RequestCallback<Boolean>() {
#Override
public void onSuccess(Boolean response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
//load new question
progress.dismiss();
}
});
}
#Override
public void onFailed(String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScanActivity.this, "Wrong Answer. Try Again!", Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
continuation...
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
Log.w("handleResult",result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText answertoQuestion = new EditText(this);
answertoQuestion.setHint("answer");
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setContentView(R.layout.activity_scan);
TextView j = (TextView)findViewById(R.id.questionhere);
EditText k = (EditText)findViewById(R.id.answerhere);
String n = k.getText().toString();
j.setText(result.getText());
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
please help me.
If you check the examples of ZXing...
In your activity XML, you can add a region for the QR scanner.
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Grab that and add the scanner view there.
public class ScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_simple_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
contentFrame.addView(mScannerView);
}
Your error is that you can't findViewById on your button when you replaced the content view with some other view that doesn't have the ID you want to find.
And even if you "switched" findViewById and setContentView around, your code wouldn't crash, but you would no longer have a button in the content view, so having the click action would be pointless.
The problem is that the button is a part of activity_scan and you set setContentView(mScannerView) to other layout.You are bound to get this error as the activity does not have a refernce to the view(button) you are refering.
What you can do is make the mScannerView a part of your main layout and then get it with findViewById();

Set text inside fragment not working after revisiting fragment

I am developing an bus time table android app. I have three fragments.
Inside first fragment I have two radio buttons i.e. From Malegaon & To Malegaon. (Malegaon is name of place).
If I select From Malegaon radio button then I am setting text to sourceEditText as Malegaon. and If I select To Malegaon radio button then I am setting text to destinationEditText as Malegaon.
This condition is working fine, when I visit fragment first time, but if I revisit fragment then From Malegaon radio Button is already selected, sourceEditText is blank and destinationEditText has text as Malegaon.
Here is my snapshot and code for first fragment.
after selecting to Malegaon radio button.
I am just changing visibility of layout. (source edittext,destination edittext,search button is one layout)
OldStandFragment.java
public class OldStandFragment extends Fragment {
public static OldStandFragment fragment ;
private static final String ARG_POSITIONS = "position";
private int positions;
private View myFragmentViewOld;
private LinearLayout fromOldMalegoanView, toOldMalegoanView;
Button selectRouteButton;
public static final String required_dest = "Please Enter Destination";
public static final String required_source = "Please Enter Source";
String language = "";
DbHelper helper;
private String sourceId = "", destinationId = "";
private ArrayList<Route> myArrayList;
private RouteAdapter routeAdapter;
private ListView routeListView;
private EditText sourceEditTextFromMalegoanOld;
private EditText destinationEditTextFromMalegoanOld;
private ImageButton searchFromMalegoanButtonOld;
private EditText sourceEditTextToMalegoanOld;
private EditText destinationEditTextToMalegoanOld;
private ImageButton searchToMalegoanButtonOld;
private RadioButton fromOldMalegoanRadioButton, toOldMalegoanRadioButton;
public OldStandFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
positions = getArguments().getInt(ARG_POSITIONS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentViewOld = inflater.inflate(R.layout.fragment_old_stand, container, false);
selectRouteButton = (Button) myFragmentViewOld.findViewById(R.id.selectRouteButton);
fromOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.fromOldMalegoanRadioButton);
toOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.toOldMalegoanRadioButton);
fromOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.fromOldMalegoanView);
toOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.toOldMalegoanView);
sourceEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.destinationEditText);
searchFromMalegoanButtonOld = (ImageButton) fromOldMalegoanView.findViewById(R.id.searchResultButton);
sourceEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.destinationEditText);
searchToMalegoanButtonOld = (ImageButton) toOldMalegoanView.findViewById(R.id.searchResultButton);
SharedPreferences prefs = getContext().getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
int a = prefs.getInt("LangValue", 0);
if (a == 0) {
language = "English";
} else {
language = "मराठी";
}
helper = new DbHelper(getContext());
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
String stopValue = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue);
fromOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (fromOldMalegoanRadioButton.isChecked()) {
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
helper = new DbHelper(getContext());
String stopValue1 = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue1);
destinationEditTextFromMalegoanOld.setText("");
}
}
});
toOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toOldMalegoanRadioButton.isChecked()) {
fromOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.GONE);
toOldMalegoanView.setVisibility(View.VISIBLE);
helper = new DbHelper(getContext());
String stopValue2 = helper.getStopName("1", language);
destinationEditTextToMalegoanOld.setText(stopValue2);
sourceEditTextToMalegoanOld.setText("");
}
}
});
searchFromMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
searchToMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
return myFragmentViewOld;
}
public static OldStandFragment newInstance(int position) {
if(fragment == null) {
fragment = new OldStandFragment();
}
Bundle bundle = new Bundle();
bundle.putInt(ARG_POSITIONS, position);
fragment.setArguments(bundle);
return fragment;
}
}
fragment_old_stand.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
android:scrollbars="vertical"
tools:context="com.ashishkudale.malegoanagar.Fragments.OldStandFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Direction or Route"
android:gravity="center"
android:textColor="#FFFFFF"
android:id="#+id/Note"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_margin="15dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/rg_ContainerOld"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="From Malegaon"
android:id="#+id/fromOldMalegoanRadioButton"
android:layout_marginLeft="5dp"
android:checked="false" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/fromOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To Malegaon"
android:id="#+id/toOldMalegoanRadioButton"
android:layout_marginLeft="5dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/toOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Select Route "
android:id="#+id/selectRouteButton"
android:background="#drawable/button_effect"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
this is Adapter to call fragment.
MyPagerAdapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Old Stand","New Stand", "Fare"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment fragment = null;
if(position ==0) {
fragment = OldStandFragment.newInstance(position);
}else if(position ==1 ){
fragment = NewStandFragment.newInstance(position);
} else if (position == 2) {
fragment = MapFragment.newInstance(position);
}
return fragment;
}
}
after revisiting OldStandFragment it look like this.
I checked with adding logs everywhere possible. And I found that after revisiting OldStandFragment, toOldMalegoanRadioButton.setOnClickListner() method is getting called.
Now I want to refresh fragment when I re-visit or any other way to solve this issue.
You have to use SharedPreferences to save state of checkbox, try this code
public class StackOne extends AppCompatActivity {
SharedPreferences prefs;
private RadioButton rButton1, rButton2;
private RadioGroup rg_ContainerOld;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stack_one);
prefs = PreferenceManager.getDefaultSharedPreferences(StackOne.this);
rButton1 = (RadioButton) findViewById(R.id.fromOldMalegoanRadioButton);
rButton2 = (RadioButton) findViewById(R.id.toOldMalegoanRadioButton);
rg_ContainerOld = (RadioGroup) findViewById(R.id.rg_ContainerOld);
GetSelectedRadioButton();
int k = prefs.getInt("rb1", 0);
if (k == 1) {
rButton1.setChecked(true);
sourceEditTextFromMalegoanOld.setText("");
} else if (k == 2) {
rButton2.setChecked(true);
sourceEditTextToMalegoanOld.setText("");
}
}
private void GetSelectedRadioButton() {
rg_ContainerOld.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.fromOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 1).commit();
break;
case R.id.toOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 2).commit();
break;
}
}
});
}
}
In your code you are dynamically setting checked state of radiobutton
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
thats why your radiobutton's oncheckedchanged method will get call. And thats why code in it.

Dynamic text depending on weather temperature - android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am a beginner in Android and hoping to achieve text being show when the weather temperature is at various temperatures. For example, if it is 5 degrees, then the text will show the user to "wear a coat".
The code is working fine, but struggling to implement this dynamic text feature. Any help will be greatly appreciated!
Java Code:
public class AdviseMe extends Activity {
private TextView cityText;
private TextView condDescr;
private TextView temp;
private TextView press;
private TextView windSpeed;
private TextView windDeg;
private TextView textview1;
private TextView hum;
private ImageView imgView;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.adviseme);
String city = "London,UK";
cityText = (TextView) findViewById(R.id.cityText);
condDescr = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.temp);
hum = (TextView) findViewById(R.id.hum);
press = (TextView) findViewById(R.id.press);
windSpeed = (TextView) findViewById(R.id.windSpeed);
windDeg = (TextView) findViewById(R.id.windDeg);
imgView = (ImageView) findViewById(R.id.condIcon);
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[]{city});
}
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params)
Weather weather = new Weather();
String data = ( (new WeatherHttpClient()).getWeatherData(params[0]));
try {
weather = JSONWeatherParser.getWeather(data);
weather.iconData = ( (new
WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0,
weather.iconData.length);
imgView.setImageBitmap(img);
}
cityText.setText(weather.location.getCity() + ", " + weather.location.getCountry());
condDescr.setText(weather.currentCondition.getCondition() + "
weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "C");
hum.setText(": " + weather.currentCondition.getHumidity() + "%");
press.setText(": " + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText(": " + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "");
}
}
}
The XML Code:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:src="#drawable/cleanbackground" />
<TextView
android:id="#+id/cityText"
style="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/condIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/cityText" />
<TextView
android:id="#+id/condDescr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/condIcon"
android:layout_alignLeft="#id/condIcon"
/>
<TextView
android:id="#+id/temp"
style="#style/tempStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_alignBaseline="#id/condDescr"
android:layout_toRightOf="#id/condDescr"/>
<TextView
android:id="#+id/pressLab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/condDescr"
android:text="Pressure"
android:layout_marginTop="15dp" />
<TextView
android:id="#+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/pressLab"
android:layout_toRightOf="#id/pressLab"
style="#style/valData"/>
<TextView
android:id="#+id/humLab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/pressLab"
android:text="Humidity" />
<TextView
android:id="#+id/hum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/humLab"
android:layout_toRightOf="#id/humLab"
android:layout_marginLeft="4dp"
style="#style/valData"/>
<TextView
android:id="#+id/windLab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/humLab"
android:text="Wind" />
<TextView
android:id="#+id/windSpeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/windLab"
android:layout_toRightOf="#id/windLab"
android:layout_marginLeft="4dp"
style="#style/valData" />
<TextView
android:id="#+id/windDeg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/windLab"
android:layout_toRightOf="#id/windSpeed"
android:layout_marginLeft="4dp"
style="#style/valData"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="124dp"
android:text="TextView" />
You need to implement a handler, which will check the Temperature variable every five seconds, based on the degrees will display a custom message in your textview. There is one more efficient method of doing this using a local broadcast
An Example of Handler would be:
public void functionA(){
//fetch value from source.
//update value to text view
//update custom textview
}
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
// Do your task here.
//Call functionA() here.
}timerHandler.postDelayed(this, 5000);
}
};
Start your handler like:
timerHandler.postDelayed(timerRunnable, 0);
Stop it like:
timerHandler.removeCallbacksAndMessages(null);
Method two use a local broadcast (More robust, less CPU consuming):
ReceiverActivity.java
An activity that watches for notifications for the event named "custom-event-name".
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
SenderActivity.java
The second activity that sends/broadcasts notifications.
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Every time a button is clicked, we want to broadcast a notification.
findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
// Send an Intent with an action named "custom-event-name". The Intent sent should
// be received by the ReceiverActivity.
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
With the code above, every time the button R.id.button_send is clicked, an Intent is broadcasted and is received by mMessageReceiver in ReceiverActivity.
The debug output should look like this:
01-16 10:35:42.413: D/sender(356): Broadcasting message
01-16 10:35:42.421: D/receiver(356): Got message: This is my message!
A dirty way of achieving what you want is:
public void functionA(){
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[]{city});
}
At your class level code the handler like:
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
functionA()
}timerHandler.postDelayed(this, 5000);
}
};
From your onCreate start it like(Anywhere in onCreate):
timerHandler.postDelayed(timerRunnable, 0);

Categories