import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
TextView t1,t2;
Button generate1;
MediaPlayer pickupgold, pickupplatinum;
SharedPreferences mySharedPreferences;
private static Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
pickupgold = MediaPlayer.create(this, R.raw.pickup_gold);
pickupplatinum = MediaPlayer.create(this, R.raw.pickup_platinum);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
OnClickButtonListener();
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
final ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
t1 = (TextView) findViewById(R.id.textView3);
t2 = (TextView) findViewById(R.id.textView8);
generate1 = (Button) findViewById(R.id.button);
generate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView userTextEntry = (TextView) findViewById(R.id.textView3);
String userData = userTextEntry.getText().toString();
int num2 = mySharedPreferences.getInt("INT_KEY1", Integer.parseInt(userData));
int num3 = mySharedPreferences.getInt("INT_KEY2", -1);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("parameter1", num2);
Random rand = new Random();
int num1 = rand.nextInt(100);
if (num1 % 2 == 0) {
pickupgold.start();
num2 += 1;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("INT_KEY1", num2);
editor.apply();
t1.setText(String.format("%d", num2));
imageView.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left));
Toast.makeText(getApplicationContext(), R.string.foundgold2, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), R.string.notfoundgold, Toast.LENGTH_LONG).show();
} if (num1 == 1){
pickupplatinum.start();
num3 += 1;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("INT_KEY2", num3);
editor.apply();
t2.setText(String.format("%d", num3));
imageView2.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left));
Toast.makeText(getApplicationContext(), R.string.foundplatinum1, Toast.LENGTH_LONG).show();
}
}
});
}
public void OnClickButtonListener() {
button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.example.tans.goldminer1.SecondActivity");
startActivity(intent);
}
}
);
}
This is MainActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
int goldamountval = intent.getIntExtra("parameter1", 0);
TextView goldamount = (TextView) findViewById(R.id.goldamount);
goldamount.setText("" + goldamountval);
}
and This is SecondActivity.java
I think the int value should be loaded from MainActivity.java but
When I go to SecondActivity, It does not seem to appear, Just showing 0.
What's the reason and how can i solve it? and Sorry, My Code may look like confused. :<
Try this on SecondActivity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("parameter1", num2);
startActivity(intent );
You need to start the SecondActivity after the first two lines :
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("parameter1", num2);
startActivity(intent);
Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, );
startActivity(intent);
Seocnd Activity-
Intent intent = getIntent();
if (null != intent) {
String stringData= intent.getStringExtra(KEY);
int numberData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue);
}
Related
I am trying to get the input from the EditText fields and store it into an SQLite database. But the Fields are null even after I enter text into it.
I did a similar thing earlier and it ended up just fine but I am confused what is causing the problem here.
package com.example.mridul.eventmanager;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CreateEvent extends AppCompatActivity {
EditText edit,edit2,edit3,edit4;
TextView t1;
ImageView img;
Button bpost;
public static final int PICK_IMAGE=1;
Uri imageuri;
Event in;
DatabaseHelper dc = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
edit = (EditText) findViewById(R.id.editText7);
edit2 = (EditText) findViewById(R.id.editText8);
edit3 = (EditText) findViewById(R.id.editText9);
edit4 = (EditText) findViewById(R.id.editText10);
t1 = (TextView) findViewById(R.id.textView6);
img = (ImageView) findViewById(R.id.imageView);
bpost = (Button) findViewById(R.id.button3);
t1.setOnClickListener(new View.OnClickListener(){
public void onClick(View vim){
operationGallery();
}
});
bpost.setOnClickListener(new View.OnClickListener(){
public void onClick(View vPost){
in.sEventName(edit.getText().toString()); //Problem here
in.sEventDesc(edit2.getText().toString());
in.sEventVenue(edit3.getText().toString());
in.sType(edit4.getText().toString());
in.sPic(imageuri.toString());
dc.addEvent(in);
Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
Intent gBack = new Intent(CreateEvent.this, LoginActivity.class);
CreateEvent.this.startActivity(gBack);
}
});
} public void operationGallery(){
Intent im = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(im , PICK_IMAGE);
}
public void onActivityResult(int requestcode, int resultcode, Intent data){
super.onActivityResult(requestcode, resultcode, data);
if((resultcode == RESULT_OK)&&(requestcode == PICK_IMAGE)){
imageuri = data.getData();
img.setImageURI(imageuri);
}
}
}
The following is the error which I am getting after executing the code
You have just forgot to initiate Event object "in"
Your Event object in is uninitialized.
In my code, I have a class for a recipe and then another class for each step. The recipe class holds an arraylist of the steps in that recipe.
I have 3 processes being called one after the other:
MainActivity calls AddEditRecipe using startActivityResult
within AddEditRecipe I have another startActivityResult which calls AddStep
within AddStep I am adding a new instance of step to the list in the recipe.
It successfully adds the object to the list before finish() is called, but when I check the size of the list when I have gone to the 2nd activity it has reverted back to 0, even though I've managed to create buttons with the data I collected from the AddStep functions.
Basically I don't know what to do make it so it everything correctly persists.
Also a heads up, I am still fairly new too java so there's probably lots of other things wrong, any random advice is greatly appreciated.
MainActivity
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button newRecipe;
Button editRecipe;
Button deleteRecipe;
LinearLayout recipeLayout;
List<NewRecipe> listOfRecipes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfRecipes = new ArrayList<>();
recipeLayout = (LinearLayout) findViewById(R.id.RecipeListLayout);
newRecipe = (Button) findViewById(R.id.NewRecipeButton);
newRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, AddRecipePopUp.class);
startActivityForResult(i,998);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==999 && resultCode == RESULT_OK){
NewRecipe rec = (NewRecipe)data.getParcelableExtra("curr_recipe");
Log.d("Number of Steps",Integer.toString(rec.listOfSteps.size()));
UpdateScreen(rec);
}
if(requestCode== 998 && resultCode == RESULT_OK){
NewRecipe recipe =(NewRecipe)data.getParcelableExtra("curr_recipe");
listOfRecipes.add(recipe);
Intent i = new Intent(MainActivity.this,AddEditRecipe.class);
i.putExtra("curr_recipe", recipe);
startActivityForResult(i,999);
}
}
void UpdateScreen(final NewRecipe recipe){
Button button = new Button(this);
button.setText(recipe.name);
button.setHeight(120);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NewRecipe recipe1 = recipe;
Button thisBut = (Button)view;
String butName = thisBut.getText().toString().toLowerCase();
for(int j = 0;j<listOfRecipes.size();j++){
String curr = listOfRecipes.get(j).name.toString().toLowerCase();
Log.d("Button ",thisBut.getText().toString());
Log.d("Current List ",listOfRecipes.get(j).name.toString().toLowerCase());
Log.d("Check bool statement", Boolean.toString(butName ==curr));
}
//recipe1 = listOfRecipes.get(0);
Intent i = new Intent(MainActivity.this, AddEditRecipe.class);
i.putExtra("curr_recipe",recipe1);
startActivityForResult(i,997);
}
});
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
recipeLayout.addView(button,lp);
}
}
AddEditRecipe
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class AddEditRecipe extends Activity {
Button home;
Button add;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_edit_recipe);
Intent i = getIntent();
final NewRecipe this_recipe = i.getParcelableExtra("curr_recipe");
Log.d("Number of Steps",Integer.toString(this_recipe.listOfSteps.size()));
LinearLayout recipeLayout = (LinearLayout) findViewById(R.id.RecipeListLayout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for(int j = 0; j<this_recipe.listOfSteps.size();j++){
Button button = new Button(this);
button.setText(this_recipe.listOfSteps.get(j).processName);
button.setHeight(120);
recipeLayout.addView(button,lp);
}
home = (Button) findViewById(R.id.HomeButton);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(AddEditRecipe.this, MainActivity.class);
i.putExtra("curr_recipe", this_recipe);
setResult(RESULT_OK,i);
Log.d("Number of Steps",Integer.toString(this_recipe.listOfSteps.size()));
finish();
}
});
add = (Button) findViewById(R.id.AddStepButton);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(AddEditRecipe.this, AddStep.class);
i.putExtra("curr_recipe", this_recipe);
startActivityForResult(i,999);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==999 && resultCode == RESULT_OK){
NewRecipe curr_rec = (NewRecipe)data.getParcelableExtra("curr_recipe");
Button button = new Button(this);
button.setText(curr_rec.listOfSteps.get(curr_rec.listOfSteps.size()-1).processName + " " + curr_rec.listOfSteps.get(curr_rec.listOfSteps.size()-1).seconds );
button.setHeight(120);
LinearLayout lay = (LinearLayout) findViewById(R.id.RecipeListLayout) ;
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lay.addView(button,lp);
}
}
}
AddStep
import android.app.Activity;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AddStep extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_step);
Intent i = getIntent();
final NewRecipe this_recipe = (NewRecipe) i.getParcelableExtra("curr_recipe");
Button finish = (Button) findViewById(R.id.AddStepButton);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText name = (EditText) findViewById(R.id.nameEditText);
EditText hours = (EditText) findViewById(R.id.HoursEditText);
EditText minutes = (EditText) findViewById(R.id.MinutesEditText);
EditText seconds = (EditText) findViewById(R.id.SecondsEditText);
this_recipe.AddStep((ConvertToSeconds(Integer.parseInt(hours.getText().toString()),Integer.parseInt(minutes.getText().toString()),Integer.parseInt(seconds.getText().toString()))),name.getText().toString());
Intent j = new Intent(AddStep.this, AddEditRecipe.class);
j.putExtra("curr_recipe", this_recipe);
Log.d("Number of Steps",Integer.toString(this_recipe.listOfSteps.size()));
setResult(RESULT_OK,j);
finish();
}
});
}
int ConvertToSeconds(int h, int m, int s){
int ans = 0;
for(int i = 0; i<h;i++){
ans+=3600;
}
for(int i = 0; i<m;i++){
ans+=60;
}
for(int i = 0; i<s;i++){
ans++;
}
return ans;
}
}
i was making an android app and i need to use one integer value in 2 activities. I tried using this code but it didn't work.
//Integer Sender
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("MyIntNameGoesHere", intValue);
startActivity(myIntent);
//Integer receiver
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
It says Cannot resolve symbol intValue and Cannot resolve symbol A and the same for B.
Here's the whole code.
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int balance;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Click counter
final TextView text = (TextView) findViewById(R.id.balance_text);
assert text != null;
// to retreuve the values from the shared preference
preferences = PreferenceManager.getDefaultSharedPreferences(this);
balance = preferences.getInt("balance", 0);
text.setText(balance + " $");
final ImageButton button = (ImageButton) findViewById(R.id.click_button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
balance++;
text.setText("" + balance + " $");
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("balance", balance);
editor.apply();
}
});
final Button UpgradesButton = (Button) findViewById(R.id.upgrades_button);
assert UpgradesButton != null;
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, UpgradesActivity.class));
}
});
//Balance Integer Sender
}
}
UpgradesActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
Error code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Receive balance from MainActivity
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(balance >= 300){ //ERROR ON THIS LINE
}
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
ALL ABOVE IS ANSWERED! ---------------------------------------------------------
Now i have problems with this part of the code:
#Override
public void onClick(View v) {
if(balance >= 300){
balance -= 300;
}
if(balance < 300){
final TextView text = (TextView) findViewById(R.id.not_enough_money_text);
assert text != null;
text.setText("You do not have enough money.");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
text.setText("");
}
}, 2000);
}
}
When i click the button it says i do not have enough money but i have over 300. Please help me.
I found out what the problem was but I'm not sure how to fix it. I need to send balance back to MainActivity. Can anyone help with that?
Send the data like this -
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UpgradesActivity.class);
intent.putExtra("key_int", balance);
startActivity(intent);
}
});
And fetch it in onCreate() of UpgradesActivity -
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
You're using different key when sending and receiving the Int.
Change this line:
int intValue = mIntent.getIntExtra("intVariableName", 0);
To this:
int intValue = mIntent.getIntExtra("MyIntNameGoesHere", 0);
I am getting a runtime exception when I am calling NavDrawerActivity from LoginScreen activity.
Error
java.lang.RuntimeException: Performing stop of activity that is not
resumed:
{com.example.owner.loginapp/com.example.owner.loginapp.NavDrawerActivity}
How to fix this error?
Here is my loginScreen code
package com.example.owner.loginapp;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.content.SharedPreferences;
public class LoginScreen extends AppCompatActivity {
ImageView image;
ImageView user_img;
ImageView pass_img;
Button log_in;
Button reg;
EditText editText_Username;
EditText editText_Pass;
UserSessionManager session;
private SharedPreferences sharedPreferences;
private static final String PREFER_NAME = "Reg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session = new UserSessionManager(getApplicationContext());
image = (ImageView) findViewById(R.id.imageView);
image.setImageResource(R.drawable.smile);
user_img = (ImageView) findViewById(R.id.user_img);
user_img.setImageResource(R.drawable.user_img);
pass_img = (ImageView) findViewById(R.id.pass_img);
pass_img.setImageResource(R.drawable.img_pass);
log_in = (Button) findViewById(R.id.btn_Login);
reg = (Button) findViewById(R.id.btn_Reg);
editText_Username = (EditText) findViewById(R.id.editText_UserName);
editText_Pass = (EditText) findViewById(R.id.editText_Password);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
image.setImageBitmap(icon);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
log_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = editText_Username.getText().toString();
String password = editText_Pass.getText().toString();
if (username.trim().length() > 0 && password.trim().length() > 0) {
String uName = null;
String uPassword = null;
if (sharedPreferences.contains("Name")) {
uName = sharedPreferences.getString("Name", "");
}
if (sharedPreferences.contains("Password")) {
uPassword = sharedPreferences.getString("Password", "");
}
if (username.equals(uName) && password.equals(uPassword)) {
session.createUserLoginSession(uName, uPassword);
Intent i = new Intent(getApplicationContext(), NavDrawerActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} else {
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.register);
Intent i = new Intent(getApplicationContext(), Reg.class);
startActivity(i);
}
});
}
}
I copied your code and tried to instantiate a Reg Activity class that I designed and everything worked fine. It is possible that you are doing something wrong in the 1onResumeoronCreate` of Reg class.
Post that class too for more information.
I want to create simple application in which i want to show bluetooth devices..but when i press the button, Application crashes..
in ActivityMain.java this method will go to next activity (Activity.java)..in which i am getting problem..Rest of buttons are working
ActivityMain.java
package com.example.bluetoothcheck5;
import java.util.Set;
import com.example.bluetoothcheck5.Activity2;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView out=(TextView)findViewById(R.id.out);
final Button button = (Button) findViewById(R.id.button1);
final Button button1 = (Button) findViewById(R.id.button2);
final Button button2 = (Button) findViewById(R.id.button3);
final Button buttonSearch = (Button) findViewById(R.id.buttonSearch);
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
out.append("device not supported");
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!mBluetoothAdapter.isDiscovering()) {
Context context = getApplicationContext();
CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.disable();
Context context = getApplicationContext();
CharSequence text = "TURNING_OFF BLUETOOTH";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : mPairedDevices)
{
Log.v("Title", "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
}
}
}
});
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(arg0.getContext(), Activity2.class);
// myIntent.setClass(MainActivity.this, Activity2.class);
// startActivityForResult(myIntent, REQUEST_PAIRED_DEVICE);
startActivity(myIntent);
}
});
}}
Activity2.java
package com.example.bluetoothcheck5;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.example.bluetoothcheck5.R;
import com.example.bluetoothcheck5.MainActivity;
public class Activity2 extends MainActivity {
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_2);
ListView mPairedListView = (ListView) findViewById(R.id.listView1);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
i made sample project to demonstrate bluetooth disovering, pair or unpair device. Find it here,
http://www.londatiga.net/it/programming/android/how-to-programmatically-scan-or-discover-android-bluetooth-device/