button click to different activity depending upon cases - android

i have static page for no internet connection....this i have to use in two actvity....the static page for no internet connection has tap to retry button...
on that tap to retry button i have to go different activity
scenerio:---------
1.when im splash activity(no internet) ---> it should load homeactvivity
2.when im contact us activity(no internet) ---> it should load contact us activity
need help how to do it???
i have got suggestion like Use some flag like isFromSplash of Boolean type which will be true when nav from splash and false when contact us...
how should i implement??????
binding.btnTaptoretry.setOnClickListener {
if (this.isDeviceOnlineStatus(this)){
if (isFromSplash==true) { //this is red `isFromSplash`
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
finish()
}
else{
val intent = Intent(this, AboutUsActivity::class.java)
startActivity(intent)
finish()
}
}
}

Splash Activity.Java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import static com.saqib.app2.RetryActivity.SOURCE;
import static com.saqib.app2.RetryActivity.SPLASH;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!Utils.isInternetConnection(this)){
Intent intent = new Intent(SplashActivity.this, RetryActivity.class);
intent.putExtra(SOURCE, SPLASH);
startActivity(intent);
finish();
return;
}
setContentView(R.layout.activity_main);
}
}
Contact activity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import static com.saqib.app2.RetryActivity.CONTACT;
import static com.saqib.app2.RetryActivity.SOURCE;
import static com.saqib.app2.RetryActivity.SPLASH;
public class ContactActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!Utils.isInternetConnection(this)){
Intent intent = new Intent(ContactActivity.this, RetryActivity.class);
intent.putExtra(SOURCE, CONTACT);
startActivity(intent);
finish();
return;
}
setContentView(R.layout.activity_contact);
}
}
Utils.Java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class Utils {
public static boolean isInternetConnection(Context context){
ConnectivityManager cm =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
}
RetryActivity.java (for retry to go to specified activity)
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
public class RetryActivity extends AppCompatActivity {
public static final String SPLASH = "SPLASH";
public static final String CONTACT = "CONTACT";
public static final String SOURCE = "SOURCE";
Button btnRetry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retry);
Intent intent = getIntent();
final String source = intent.getExtras().getString(SOURCE);
btnRetry = findViewById(R.id.btnRetry);
btnRetry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Utils.isInternetConnection(RetryActivity.this)) {
switch (source) {
case SPLASH:
startActivity(new Intent(RetryActivity.this, SplashActivity.class));
finish();
break;
case CONTACT:
startActivity(new Intent(RetryActivity.this, ContactActivity.class));
finish();
break;
}
}
}
});
}
}
Used Intent to send data and receive either it comes from splash or contact.
Intent intent = getIntent();
final String source = intent.getExtras().getString(SOURCE);
This is the magic from where get the history. From where it came.

Use this code
class MainActivity : AppCompatActivity(){
lateinit var button : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button1)
button.setOnClickListener(listener)
}
val listener= View.OnClickListener { view ->
when (view.getId()) {
if(view.getid == R.id.button1)-> {
// Do some work here
}
}
}
}

Related

close the started activity in my case

I have a class which doesn't extend Activity or Fragment. It is a independent class. I would like to use that class to control an Activity start and finish.
public class MyActivityManager() {
public MyActivityManager(Context context) {
mContext = context;
}
public void startMainActivity() {
Intent intent = new Intent(mContext, MainActivity.class);
mContext.startActivity(intent);
}
public void closeMainActivity() {
// how can I close the started main activity from the other function here?
}
}
As you can see, I started MainActivity from one function, and in another function, I would like to close the MainActivity started. But how can I have a reference to the started MainActivity?
(My main purpose is to let upper caller to use this MyActivityManager to start and close MainActivity)
If the current way is not possible, how to achieve what I want?
//Try the below code and let me know if any issues.
package com.example.raghavendrapai.myapplication;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mCloseReceiver, new IntentFilter("close_main_activity"));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mCloseReceiver);
}
private BroadcastReceiver mCloseReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("close_main_activity")) {
finish();
}
}
};
}
// And in your class
package com.example.raghavendrapai.myapplication;
import android.content.Context;
import android.content.Intent;
/**
* Created by raghavendra.pai on 08/03/18.
*/
public class MyActivityManager {
private Context mContext;
public MyActivityManager(Context context) {
mContext = context;
}
public void startMainActivity() {
Intent intent = new Intent(mContext, MainActivity.class);
mContext.startActivity(intent);
}
public void closeMainActivity() {
Intent intent = new Intent("close_main_activity");
mContext.sendBroadcast(intent);
}
}

SharedPreference is not working in checkbox

I want to fill the TextView of another activity based on preference on checkBox event but its working please help me to sort the issue..It is forcefully stopping.Please help in the if else statement part .what we need to write in activity 2 to select based on the checkBox in activity 1
Activity 1:
package com.example.rajatanurag.shoppingsites;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class Book extends AppCompatActivity {
Button b1,b2;
public static CheckBox cb1,cb2,cb3;
TextView tv1,tv2,tv3;
SharedPreferences sp1;
ImageView iv1,iv2,iv3;
String x,y,z;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);
cb3=(CheckBox)findViewById(R.id.cb3);
tv1=(TextView)findViewById(R.id.tv4);
tv2=(TextView)findViewById(R.id.tv2);
tv3=(TextView)findViewById(R.id.tv3);
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
}
public void OnClick1(View view)
{
SharedPreferences.Editor editor = sp1.edit();
if(cb1.isChecked()==true) {
editor.putString("price1", tv1.getText().toString());
editor.putBoolean("x",true);
}
if(cb2.isChecked()==true)
{
editor.putString("price2",tv2.getText().toString());
editor.putBoolean("y",true);
}
if(cb3.isChecked()==true)
{
editor.putString("price3",tv3.getText().toString());
editor.putBoolean("z",true);
}
editor.commit();
Intent i=new Intent(this,MyCart.class);
startActivity(i);
}
}
2.Activity
package com.example.rajatanurag.shoppingsites;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MyCart extends AppCompatActivity {
SharedPreferences sp1;
TextView tv4,tv5,tv6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart);
tv4=(TextView)findViewById(R.id.tv4);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
if(Book.cb1.isChecked()==true){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(Book.cb1.isChecked()==true){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(Book.cb1.isChecked()==true){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
}
}
You shouldn't be using static variables for view members because you might get memory leaks. Also the views you are referencing are destroyed when activity is destroyed, so they are not accessible in your second activity. You can send checkboxes checked values as intent extras.
Put this in your Activity 1 in OnClick1() method:
Intent i=new Intent(this,MyCart.class);
i.putExtra("cb1", cb1.isChecked());
i.putExtra("cb2", cb2.isChecked());
i.putExtra("cb3", cb3.isChecked());
startActivity(i);
This is how you get values in Activity 2 (in onCreate() method):
Intent intent = getIntent();
if(intent.getBooleanExtra("cb1", false)){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(intent.getBooleanExtra("cb2", false)){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(intent.getBooleanExtra("cb3", false)){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
public void OnClick1(View view)
{
if(view.getID() == R.id.cb1)
{
if(cb1.isChecked())
editor.putBoolean("x",true);
else
editor.putBoolean("x",false);
}
}
In your second activity
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
boolean isChecked = sp1.getBoolean("x", false);
if(isChecked){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}

Issue running a simple login app

I was learning to make a simple login app from youtube, however, when I build the code, although the app runs quite fine but it never assigns the value of 3 to the attempt counter later in the code, only the layout is visible and hence login doesn't work. Can you please help me? If you need any other file, write it in comment, I'll upload it later. Thanks.
package com.shubham.splashscreenemulation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
}
You don't call the function LoginButton() in your Activity.
Here some tips : function name starts with lowercase letter like loginButton ( with camelCase ), classes names starts with uppercase letter like AppCompatActivity. This tip is for more readability for the code. Why do you declare Views as static in that function?
package com.shubham.splashscreenemulation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
LoginButton();
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
You can add LoginButton() after setContentView or remove the LoginButton method, move everything inside onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--; attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
});
}
You can also change your setText to this attempts_left.setText(attempt_counter+"");

Getting NetworkOnMainThreadException creating socket in AsyncTask

how is possible that I am getting android.os.NetworkOnMainThreadException when I try to create a socket calling bulb.connectToHW() if I do it from the doInBackground() method of my asycTask?
This is the code of the AsyncTask:
package com.example.bulbcontrol2;
import java.net.InetAddress;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.widget.TextView;
public class AsyncConnection extends AsyncTask<Object, String, String> {
private TextView textV;
private Context context;
private String message;
private Device bulb;
public AsyncConnection(TextView textViewToUpdate,Context context)
{
this.textV = textViewToUpdate;
this.context = context;
}
#Override
protected String doInBackground(Object... params) {
bulb = new Device((InetAddress) params[0],(Integer) params[1]);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("open_connection"))
{
System.out.println(bulb.connectToHW());
message = "Connected";
System.out.println(bulb.dataTransferHW("hello"));
textV.setText(message);
}
if (intent.getAction().equals("close_connection"))
{
message = "Disconnected";
System.out.println(bulb.dataTransferHW("bye"));
bulb.closeConexHW();
}
}
};
IntentFilter filter = new IntentFilter("open_connection");
context.registerReceiver(receiver, filter);
filter.addAction("close_connection");
context.registerReceiver(receiver, filter);
return message;
}
/* protected void onProgressUpdate(String... progress) {
//textV.setText(progress[0]);
}*/
}
And this is the code of the UIThread :
package com.example.bulbcontrol2;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends Activity
{
Intent broadcastIntent = new Intent();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bulbActions();
}
public void bulbActions()
{
final ToggleButton buttonBulb = (ToggleButton) findViewById(R.id.ToggleBulb);
final ToggleButton buttonLDR = (ToggleButton) findViewById(R.id.ToggleLDRValues);
final TextView txtLDR = (TextView) findViewById(R.id.TxtLDRValues);
byte [] hostBytes = new byte[] {(byte)192,(byte)168,(byte)0,(byte)12};
int port = 5006;
InetAddress host = null;
try
{
host = InetAddress.getByAddress(hostBytes);
}
catch (UnknownHostException e)
{
System.out.println("\nError with server address");
e.printStackTrace();
}
new AsyncConnection((TextView)findViewById(R.id.TxtLDRValues),this.getApplicationContext()).execute(host,port);
buttonBulb.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
if (buttonBulb.isChecked())
{
System.out.println("Pulsado");
broadcastIntent.setAction("open_connection");
MainActivity.this.sendBroadcast(broadcastIntent);
}
else
{
System.out.println("NO Pulsado");
broadcastIntent.setAction("close_connection");
MainActivity.this.sendBroadcast(broadcastIntent);
}
}
});
}
}
Your doInBackground is just defining a BroadcastReceiver and registering it. All the code inside onReceive will run in the main thread when the system calls it following your onClick.
I don't know why you need a BroadcastReceiver if you're just triggering it from a button.
Instead you could do the network stuff directly on your doInBackground and then actually start the AsyncTask inside onClick.
On a case you do need a BroadcastReceiver what you wanna do is start a service from onReceive and do all the network job in the service.
After API11 you can also use goAsync() in the receiver as described here and start a Thread.

Making a call when button pressed on Arduino

Hi I'm trying to combine 2 projects
1. that tells me wen button on arduino pressed
2. make a call on android
what im trying to do is when button pressed on arduino make a call..
but with no luck :(
Call
package net.mitchtech.adb;
import net.mitchtech.adb.simpledigitalinput.R;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class phonecalls extends Activity {
private void call() {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:048598077"));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
}
}
buttons
package net.mitchtech.adb;
import net.mitchtech.adb.simpledigitalinput.R;
import net.mitchtech.adb.phonecalls;
import org.microbridge.server.AbstractServerListener;
import org.microbridge.server.Server;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
public class ButtonView extends FrameLayout {
private static final String TAG = ButtonView.class.getSimpleName();
private final View mButtonView;
private Server mServer;
private final int BUTTON1 = 2;
private final int BUTTON2 = 3;
public ButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mButtonView = inflater.inflate(R.layout.input, this);
}
public void setServer(Server server) {
mServer = server;
mServer.addListener(new AbstractServerListener() {
#Override
public void onReceive(org.microbridge.server.Client client, byte[] data) {
if (data.length < 2)
return;
final int pinNumber = data[0];
final int pinState = data[1];
Log.i(TAG, "data[0]:" + pinNumber + " data[1]:" + pinState);
final TextView positionText = (TextView) findViewById(R.id.activeText);
class InputAction implements Runnable {
public void run() {
switch (pinNumber) {
case BUTTON1:
if (pinState == 1) {
call();
positionText.setText("Button 1 Active");
} else {
positionText.setText("");
}
break;
case BUTTON2:
if (pinState == 1) {
positionText.setText("Button 2 Active");
} else {
positionText.setText("");
}
break;
default:
break;
}
}
};
InputAction action = new InputAction();
post(action);
}
});
}
public View getmButtonView() {
return mButtonView;
}
}
and another activity
package net.mitchtech.adb;
import java.io.IOException;
import net.mitchtech.adb.simpledigitalinput.R;
import org.microbridge.server.Server;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class SimpleDigitalInputActivity extends Activity {
private final static String TAG = SimpleDigitalInputActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Server server = null;
try
{
server = new Server(4567);
server.start();
ButtonView buttonView = (ButtonView) findViewById(R.id.inputView);
buttonView.setServer(server);
} catch (IOException e)
{
Log.e(TAG, "Unable to start TCP server", e);
System.exit(-1);
}
}
}
Your call() function is declared in your activity, but you're trying to access it in your ButtonView class. Try moving it into ButtonView (copy & paste).

Categories

Resources