I've seen a few related topics on here but after many attempts I just couldn't seem to find the solution so hopefully someone out there can help. Here's my code so far (Trying to make userInput appear on the 2nd activity as the result):
MainActivity.java
package winfield.joe.wind.v1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
// public var
private EditText text;
// default func
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
// findViewById = Finds a view that was identified by the id attribute
// from the XML that was processed in onCreate(Bundle).
// (EditText) = typecast
text = (EditText) findViewById(R.id.userInput);
}
//Will be executed by clicking on the calculate button because we assigned "calc" to the "onClick" Property
public void calc(View view) {
RadioButton toKilometers = (RadioButton) findViewById(R.id.toKilometers);
RadioButton toKnots = (RadioButton) findViewById(R.id.toKnots);
if (text.getText().length() == 0) {
// if the text field is empty show the message "enter a valid number" via toast message
Toast.makeText(this, "enter a valid number", Toast.LENGTH_LONG).show();
} else {
int userInput = R.string.userInput;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("userInput", userInput);
startActivityForResult(i, 0);
startActivity(i);
// parse input Value from Text Field
double inputValue = Double.parseDouble(text.getText().toString());
// convert to...
if (toKilometers.isChecked()) {
text.setText(String.valueOf(convertToKM(inputValue)));
// uncheck "to km" Button
toKilometers.setChecked(false);
// check "to knots" Button
toKnots.setChecked(true);
} else { /* if toKnots button isChecked() */
text.setText(String.valueOf(convertToKnots(inputValue)));
// uncheck "to knots" Button
toKnots.setChecked(false);
// check "to km" Button
toKilometers.setChecked(true);
}
}
}
/*private void putExtra(String string, int result) {
// TODO Auto-generated method stub
}*/
private double convertToKM(double inputValue) {
// convert knots to km
return (inputValue * 1.8);
}
private double convertToKnots(double inputValue) {
// convert km to knots
return (inputValue * 0.539956803);
}
}
SecondActivity.java
package winfield.joe.wind.v1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
Intent i = getIntent();
String userInput = i.getStringExtra("userInput");
}
//onClick GoBack method assigned to the Go Back? button which returns the user to main activity from the second activity
public void GoBack(View view) {
//AlertDialog appears upon the onclick of the go back button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
// set dialog message
builder .setCancelable(false)
.setPositiveButton("Convert Again",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to Main Activity
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent);
}
})
.setNeutralButton("Back to Home",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to the home page
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
})
.setNegativeButton("View Results",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical">
<!--TITLE-->
<TextView
android:id="#+id/titleMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="22dp"
android:gravity="center"
android:text="#string/titleMain"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="30sp" />
<!--USER-INPUT-->
<EditText
android:id="#+id/userInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:hint="#+string/userInput"
android:inputType="numberDecimal"
android:paddingEnd="40dp"
android:paddingStart="20dp"
android:paddingTop="30dp" >
<requestFocus />
</EditText>
<!--TWO RADIO BUTTONS-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!--toKNOTS-->
<RadioButton
android:id="#+id/toKnots"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.04"
android:checked="true"
android:text="#string/toKnots" />
<!--toKM-->
<RadioButton
android:id="#+id/toKilometers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="20dp"
android:layout_marginTop="10dp"
android:text="#string/toKilometers" />
</LinearLayout>
<!--CALCULATE-->
<Button
android:id="#+id/calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:onClick="calc"
android:text="#string/calc" />
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<!-- TITLE -->
<TextView
android:id="#+id/titleResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="#string/titleResults"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="25sp" />
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="#string/result"
android:textColorHint="#color/textColor" >
<requestFocus />
</TextView>
<Button
android:id="#+id/GoBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/GoBack"
android:onClick="GoBack" />
</LinearLayout>
Change this...
int userInput = R.string.userInput;
...to...
String userInput = text.getText().toString();
Everything in the R.java file is a static final int which is used to reference a resource - it isn't actually the resource itself (or the contents of the resource in the case of an EditText for example).
**This is the correct way to change information between 2 activity, of corse be careful to activity lifecycle. This code best practice!**
First activity
public class MainActivity extends Activity {
private static final String Tag = "ACTIVITY";
private static final String CONTATORE = "contatore";
TextView et;
Button btn,btnLancia;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (TextView) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btn);
btnLancia = (Button) findViewById(R.id.btnLancia);
if(savedInstanceState != null){
counter = savedInstanceState.getInt(CONTATORE);
}
btnLancia.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lanciaActivity();
}
});
et.setText("" + counter);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
++counter;
et.setText("" + counter);
}
});
Log.d(Tag, "OnCreate");
}
protected void lanciaActivity() {
Intent intent = new Intent(this,Activity2.class);
Bundle bundle = new Bundle();
bundle.putInt(Activity2.VALUE, counter);
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(Tag, "OnDestroy");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d(Tag, "OnPause");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d(Tag, "OnRestart");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Log.d(Tag, "onRestoreInstanceState");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d(Tag, "OnResume");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.d(Tag, "OnSaveIstantState");
outState.putInt(CONTATORE, counter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d(Tag, "OnStart");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d(Tag, "OnStop");
}
}
SECONd ACTIVITY
public class Activity2 extends Activity {
private static final String Tag = "ACTIVITY2";
public static final String VALUE = "value";
private static final String VALOREATT = "val";
TextView contatore;
Button button;
int contatoreq;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity2);
Log.d(Tag, "OnCreate");
contatore = (TextView) findViewById(R.id.textView1);
button = (Button) findViewById(R.id.btnDoppio);
if(savedInstanceState!=null){
contatoreq = savedInstanceState.getInt(VALOREATT);
}
else {
Intent intetn = getIntent();
Bundle bundle = intetn.getExtras();
if(bundle!=null)
contatoreq = bundle.getInt(VALUE);
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
contatoreq = contatoreq*2;
contatore.setText("" + contatoreq);
}
});
contatore.setText("" + contatoreq);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(Tag, "OnDestroy");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d(Tag, "OnPause");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d(Tag, "OnRestart");
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Log.d(Tag, "onRestoreInstanceState");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d(Tag, "OnResume");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.d(Tag, "OnSaveIstantState");
outState.putInt(VALOREATT, contatoreq);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d(Tag, "OnStart");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d(Tag, "OnStop");
}
}
I see two problems in your code.
First you are setting userInput to R.string.userInput which is kind of strange imo. You should set userInput to the text from the TextField:
String userInput = text.getText().toString();
The second problem I notice is that you start the second intent twice. Once for result and once without:
startActivityForResult(i, 0);
startActivity();
Try to remove the startActivityForResult if you do not want to work with the result from the last activity. You probably misunderstood was startActivityForResult(i, 0) does.
You basically call startActivityForResult() if you want to get the result back from the activity. For example you are in your MainActivity and want to display a photo in there. Now you can start the camera intent with startActivityForResult() and after the photo is taken you can process this in your MainActivity.
If you just want to pass the value to the next activity a simple startActivity() is enough. Here is the link to the docs if you want to read more about this topic:
startActivityForResult() - Documentation
Related
I have a fragment with this view:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:tag="general"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#343535"
android:orientation="vertical"
tools:context=".fragments.GeneralFragment">
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
<Button
android:id="#+id/observed"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/observed" />
<Button
android:id="#+id/thanks"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/thanks" />
</LinearLayout>
There are 3 buttons. Whenever you click on one of them, its text will be displayed.
Now I would like to add another button but dynamically. It should be added before #+id/hello.
I have tried it with
LinearLayout root = (LinearLayout) view.findViewById(R.id.root);
root.addView();
but it looks completely wrong since some parameters are missing.
For instance, the new button should be like:
XML:
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="I am a dynamic text" />
This button should be saved permanently in the app. How can I do this?
Update
I am using a dialog, so this is the class:
#SuppressLint("ValidFragment")
public class Dialog extends DialogFragment {
private final int _layout;
private TextInputEditText _customTextField;
#SuppressLint("ValidFragment")
public Dialog(int layout) {
_layout = layout;
}
public interface ICustomTts {
void customTts(String input, Activity activity);
}
public ICustomTts iCustomTts;
public interface ITarget {
void getTarget(String input);
}
public ITarget iTarget;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(_layout, container, false);
// Display fragment_custom
if (_layout == R.layout.fragment_custom) {
_customTextField = view.findViewById(R.id.customTextField);
Button _customBtn = view.findViewById(R.id.customCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of custom");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iCustomTts.customTts(input, getActivity());
_dismiss();
}
}
});
MaterialCheckBox customeSave = view.findViewById(R.id.customSave);
customeSave.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
Log.d(TAG, "customeSave was clicked!");
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(getContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
}
});
}
// Display fragment_target
if (_layout == R.layout.fragment_target) {
_customTextField = view.findViewById(R.id.targetTextField);
Button _customBtn = view.findViewById(R.id.targetCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of target");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iTarget.getTarget(input);
_dismiss();
}
}
});
}
return view;
}
/**
* Dismissing the dialog
*/
private void _dismiss() {
this.dismiss();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if (_layout == R.layout.fragment_custom) {
iCustomTts = (ICustomTts) getActivity();
}
else if (_layout == R.layout.fragment_target) {
iTarget = (ITarget) getActivity();
}
}
catch (ClassCastException e) {
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
}
}
}
You need to use the two-argument version of addView() to determine the order (index) of the button inside the LinearLayout:
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(requireContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
I am new to android development and I am confused about how to add admob banner to a fragment activity(I think its calling fragment). I am modifying a source code.
I have a layout file called fragment_ftp.xml and its as below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=""
android:id="#+id/statusText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="99dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/ftpAddressText"
android:layout_below="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_ftp"
android:id="#+id/startStopButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/primary_red"
android:text=""
android:id="#+id/warningText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ftp_image"
android:layout_above="#+id/warningText"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_home_footer" />
</RelativeLayout>
</RelativeLayout>
I had added the admob banner and in the preview, I can see that. Please check the below screenshot.
But the issues is that, Where should I write the java code for this admob banner. I don't have a corresponding activity for this fragment_ftp.xml.
Searching for fragment_ftp, I could see only a java file as follows.
FTPServerFragment.java
package com.filename.fragments;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
I this the java page where I shall write the admob call?
try and use this code solve the issue
http://www.androidhive.info/2016/02/android-how-to-integrate-google-admob-in-your-app/
your code java has to be added inside onCreateView function in FTPServerFragement like this :
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
//your ads
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = rootView.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
I just wanted to know, if there is a better way to use setOnClickListener for several buttons and reduce redundant code.
Here is my code:
private void addListenerOnColorButtons() {
redButton = (Button) findViewById(R.id.buttonRed);
redButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (!red) {
Toast.makeText(Register.this, "Red is selected!",
Toast.LENGTH_SHORT).show();
red = true;
} else {
red = false;
}
}
});
blueButton = (Button) findViewById(R.id.buttonBlue);
blueButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (!blue) {
Toast.makeText(Register.this, "Blue is selected!",
Toast.LENGTH_SHORT).show();
blue = true;
} else {
blue = false;
}
}
});
greenButton = (Button) findViewById(R.id.buttonGreen);
greenButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (!green) {
Toast.makeText(Register.this, "Green is selected!",
Toast.LENGTH_SHORT).show();
green = true;
} else {
green = false;
}
}
});
}
Any help would be greatly appreciated.
All you need is to implement your activity the
OnClickListener
and adjust your code with the following structure :
private void attachListenersOnColorButtons() {
redButton = (Button) findViewById(R.id.buttonRed);
redButton.setTag("RedButton"); // this tag will be used as identifier in onClick method
redButton.setOnClickListener(this);
blueButton = (Button) findViewById(R.id.buttonBlue);
blueButton.setTag("BlueButton");
blueButton.setOnClickListener(this);
greenButton = (Button) findViewById(R.id.buttonGreen);
greenButton.setTag("GreenButton");
greenButton.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
if(v.getTag().equals("RedButton")){
// actions when red button is pressed
}else if(v.getTag().equals("BlueButton")){
// corresponding actions for blue button
}else if(v.getTag().equals("GreenButton"){
// ...
}
}
Make your class implement onClickListener, override the OnClickListener() method in the class.
You can do in this way :
public class MainActivity extends Activity implements OnClickListener
{
private Button redButton;
private Button greenButton;
private int clickedButtonTag;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.avticity_compte);
redButton = (Button) findViewById(R.id.redButton);
greenButton = (Button) findViewById(R.id.greenButton);
redButton.setOnClickListener(this);
greenButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.redButton:
case R.id.greenButton:
clickedButtonTag = Integer.parseInt((String) view.getTag());
break;
default:
break;
}
}
}
Yes there is a way.
In your layout file set clickable property of all the buttons and give same method name in all the buttons:
<Button
android:id="#+id/buttonBlue"
...
android:clickable="true"
android:onClick="onClick"/>
...
<Button
android:id="#+id/buttonGreen"
android:clickable="true"
android:onClick="onClick"/>
In your activity create a method with name onClick like this:
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonBlue:
// Blue button code
break;
case R.id.buttonGreen:
// Green button code
break;
case R.id.buttonRed:
// Red button code
break;
default:
}
}
xml
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="18dp"
android:text="red" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:text="blue" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:text="green" />
Activity
public class MainActivity extends Activity implements OnClickListener{
public Button redButton,blueButton,greenButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
redButton=(Button)findViewById(R.id.button1);
blueButton=(Button)findViewById(R.id.button2);
greenButton=(Button)findViewById(R.id.button3);
redButton.setOnClickListener(this);blueButton.setOnClickListener(this);greenButton.setOnClickListener(this);
}
#Override
public void onClick(View arg0)
{
Toast.makeText(MainActivity.this, ((Button)arg0).getText()+" is selected", 0).show();
}
}
Looks like you want 3 toggle buttons, then you don't need the booleans and your users will have some visual feedback: http://developer.android.com/guide/topics/ui/controls/togglebutton.html.
The main way to avoid duplicate code is to extract the common code in to functions. Determine the differences and pass them in to these functions as parameters. The below demonstrates this even if you choose to stay with Button.
Note I only have to have three clicked functions because of the toast, so if that's debug, it can all be one:
XML:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRedToggleClicked"/>
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onGreenToggleClicked"/>
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onBlueToggleClicked"/>
Activity:
public void onRedToggleClicked(View view) {
colourToggleChanged((ToggleButton) view), "Red");
}
public void onGreenToggleClicked(View view) {
colourToggleChanged((ToggleButton) view), "Blue");
}
public void onRedToggleClicked(View view) {
colourToggleChanged((ToggleButton) view), "Green");
}
private void colourToggleChanged(ToggleButton toggle, String colourName) {
// Is the toggle on?
boolean on = toggle.isChecked();
if (on)
Toast.makeText(this, colourName + " is selected!",
Toast.LENGTH_SHORT).show();
}
I work on an app this sending a sms and showing the received sms as an AlertDialog but AlertDialog Not be shown when receiving SMS
here is the Code Of my project:
MainActivity:
package com.am7.masirinfo;
public class MainActivity extends Activity {
TextView tv;
SharedPreferences prefs;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton btn2 = (ImageButton) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8A0441")));
bar.show();
bar.setIcon(R.drawable.bar);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayUseLogoEnabled(true);
bar.setDisplayHomeAsUpEnabled(false);
TextView tx = (TextView)findViewById(R.id.textView1);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font.ttf");
tx.setTypeface(custom_font);
TextView tx1 = (TextView)findViewById(R.id.textView2);
Typeface custom_font1 = Typeface.createFromAsset(getAssets(), "fonts/gmail.ttf");
tx1.setTypeface(custom_font1);
TextView tx2 = (TextView)findViewById(R.id.textViewMessage);
tx2.setTypeface(custom_font);
TextView tx3 = (TextView)findViewById(R.id.textView3);
TextView tx4 = (TextView)findViewById(R.id.textView4);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
txtMessage = (EditText) findViewById(R.id.editTextSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
} protected void sendSMSMessage() {
Log.i("Send SMS", "");
String phoneNo = txtphoneNo.getText().toString();
String message = txtMessage.getText().toString();
try { SmsManager smsManager =
SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
AlertDialog ad1 = new AlertDialog.Builder(this).create();
ad1.setCancelable(false);
// This blocks the 'BACK' button
ad1.setMessage("با موفقیت ارسال شد");
ad1.setTitle("انجام شد");
ad1.setButton("باش", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad1.show();
ad1.setCanceledOnTouchOutside(true);
}
catch (Exception e) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false);
// This blocks the 'BACK' button
ad.setMessage("متاسفانه ارسال نشد مجددا تلاش کنید.");
ad.setTitle("خطایی رخ داد!");
ad.setButton("خب", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
ad.setCanceledOnTouchOutside(true);
e.printStackTrace();
}
}
#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;
}
}
and this is the SmsReceiver.java :
public class SmsReceiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if
(bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + phoneNumber + "; message: " + message);
if
(TextUtils.equals(currentMessage.getDisplayOriginatingAddress(), "+981000141")) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("اطلاعات ریافت شد!");
builder.setMessage(message);
builder.setPositiveButton("HEY!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
builder.show();
}
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
private CharSequence contains(String string) {
// TODO Auto-generated method stub
return null;
}
}
Main_layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sms_label" />
<EditText
android:id="#+id/editTextSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="����: 0711 0511 ���� ����� �� ����"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnSendSMS"
android:layout_width="fill_parent"
android:layout_height="41dp"
android:background="#drawable/abstract_877"
android:text="#string/send_sms_label" />
<EditText
android:id="#+id/editTextPhoneNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:enabled="false"
android:inputType="phone"
android:text="+981000141"
android:visibility="invisible" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="����� �� ���� ��� ���� � Ӂ� �� �� � ����� �� ��� ���� �� ���� ������."
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textColorHint="#00BD39" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom|center"
android:text="AM7group#gmail.com" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="www.iran141.ir"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="+981000141"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageButton
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="339dp"
android:background="#android:color/transparent"
android:src="#drawable/exitbtn" />
Logcat:
05-26 20:16:53.509: I/SmsReceiver(31910): senderNum: +981000141; message: عجبا
05-26 20:16:53.529: I/SmsReceiver(31356): senderNum: +981000141; message: عجبا
05-26 20:16:53.639: E/SmsReceiver(31356): Exception smsReceiverandroid.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
After along conversation with #faizal I changed the main activity but I got 2 errors once in MainActivity:
public class MainActivity extends Activity {
TextView tv;
SharedPreferences prefs;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
SmsReceiver BR_smsreceiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BR_smsreceiver = new SmsReceiver();
BR_smsreceiver.setActivityHandler(this);
IntentFilter fltr_smsreceived = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(BR_smsreceiver, fltr_smsreceived);
ImageButton btn2 = (ImageButton) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8A0441")));
bar.show();
bar.setIcon(R.drawable.bar);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayUseLogoEnabled(true);
bar.setDisplayHomeAsUpEnabled(false);
public void showAlert(string message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(" !");
builder.setMessage(message);
builder.setPositiveButton("HEY!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
builder.show();
}
TextView tx = (TextView)findViewById(R.id.textView1);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font.ttf");
tx.setTypeface(custom_font);
TextView tx1 = (TextView)findViewById(R.id.textView2);
Typeface custom_font1 = Typeface.createFromAsset(getAssets(), "fonts/gmail.ttf");
tx1.setTypeface(custom_font1);
TextView tx2 = (TextView)findViewById(R.id.textViewMessage);
tx2.setTypeface(custom_font);
TextView tx3 = (TextView)findViewById(R.id.textView3);
TextView tx4 = (TextView)findViewById(R.id.textView4);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
txtMessage = (EditText) findViewById(R.id.editTextSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
} protected void sendSMSMessage() {
Log.i("Send SMS", "");
String phoneNo = txtphoneNo.getText().toString();
String message = txtMessage.getText().toString();
try { SmsManager smsManager =
SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
AlertDialog ad1 = new AlertDialog.Builder(this).create();
ad1.setCancelable(false);
// This blocks the 'BACK' button
ad1.setMessage("�� ������ ����� ��");
ad1.setTitle("����� ��");
ad1.setButton("���", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad1.show();
ad1.setCanceledOnTouchOutside(true);
}
catch (Exception e) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false);
// This blocks the 'BACK' button
ad.setMessage("�������� ����� ��� ����� ���� ����.");
ad.setTitle("����� �� ���!");
ad.setButton("��", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
ad.setCanceledOnTouchOutside(true);
e.printStackTrace();
}
}
#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;
}
}
The Error is in public void method.
And twice error is in SmsReceiver but this problem is for this problem!
Here you are #faizal
Thanks in advance
The problem is that the context being supplied to the onReceive method of the BroadcastReceiver is an application context(as opposed to activity context), which cannot be used to show a dialog box apparently. So you need to show the dialog in your running activity instead of in the broadcast receiver.
In your SmsReceiver class, create a function to receive the main activity class object :
MainActivity act = null;
void setActivityHandler(MainActivity act)
{
this.act=act;
}
Register the broadcast receiver in the main activity(instead of in the splash screen) and call setActivityHandler(). So you will have the following lines in your main activity :
SmsReceiver BR_smsreceiver = null;
onCreate(Bundle savedInstance){
....
BR_smsreceiver = new SmsReceiver();
BR_smsreceiver.setActivityHandler(this);
IntentFilter fltr_smsreceived = new
IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(BR_smsreceiver, fltr_smsreceived);
....
}
In your SmsReceiver class, remove all the AlertDialog builder lines and replace it with
act.showAlert(message);
In your main activity class, create the showAlert() :
public void showAlert(String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("اطلاعات ریافت شد!");
builder.setMessage(message);
builder.setPositiveButton("HEY!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
builder.show();
}
How do i make a button open a activity if the rest of my buttons are linked to web pages with a onClickListener?
I go the webpages to open correctly in eclipse by using:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1=(Button)findViewById(R.id.button1);
public void onClick(View v) {
// TODO Auto-generated method stub
sendToCoaches();
}
private void sendToCoaches() {
// TODO Auto-generated method stub
String url = "http://www.signal5crossfit.com/coaches/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(android.net.Uri.parse(url));
startActivity(i);
}
});
b7.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
sendToContacts();
}
public void sendToContacts() {
Intent intent = new Intent(AppActivity.this, App2Activity.class);
startActivity(intent);
}
});}}
I changed it to the second example that you up in to include the onClick in my xml file and this is the error i get.
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.Signal5.android/com.Signal5.android.App2Activity}: java.lang.NullPointerException
Does that mean its pointing to nowhere?
I'm guessing you're using android:onClick="onClick" in your xml layout.
Example:
<Button android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
android:onClick="onClick" />
<Button android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:onClick="onClick" />
You can check which view was clicked by getting its id: View.getId().
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
sendToCoaches();
break;
case R.id.button2:
doSomethingElse();
break;
}
}
Another way of doing this would be to set a View.OnClickListener for each button:
Button b1 = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
sendToCoaches();
}
});
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
doSomethingElse();
}
});