i have an app that has a int called Money and i .putExtra it to go to another class but every time i push the button to go to that class it forces close the app.
here is the code i used to send the int
int Money = 0;
GoToSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(), settings.class);
intent.putExtra("money",Money);
startActivity(intent);
}
});
and here is where i receive it and try to save it
public class settings extends Activity {
int LoadDef = 0;
Button Save,Load,ClsSave;
Intent intent = getIntent();
int Money = intent.getIntExtra("money", 0);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Save = (Button) findViewById(R.id.Save);
Load = (Button) findViewById(R.id.Load);
ClsSave = (Button) findViewById(R.id.ClsSave);
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences=getSharedPreferences("MoneySave", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("MoneySave", Money);
editor.commit();
}
});
could someone help me fine out why it forces close?
The problem is here :
Intent intent = getIntent();
you should get extra from your intent , in onCreate() not in class definition
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Intent intent = getIntent();
int Money = intent.getIntExtra("money", 0);
Related
I have tried everything and whatever I could to solve this problem. At last I am posting it here to get a solution (New to Android).
I have made an android scanner app and I am using ZXing open source code. The problem is after scan I am trying to send the scan result to another activity but unable to do.
Here is my code:
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler, NavigationView.OnNavigationItemSelectedListener {
private ZXingScannerView mScannerView;
private int CALL_SCANNER_APP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Scan Button code
public void onClick(View v) {
ZXingScannerView mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
//startActivityForResult(mScannerView1, CALL_SCANNER_APP);
}
#Override
protected void onPause (){
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
ResultActivity.tvresult.setText(result.getText());
/*Log.w("handleReuslt", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
//alertDialog.show();
builder.setPositiveButton("Result", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("OK", null).show();*/
//Resume Scanning
//mScannerView.resumeCameraPreview(this);
}
There is one method which send results from One activity to other activity is scanActivityForResult() but in my case I am not using intent on public void onClick(View v)
So how do I achieve this.
Thanks!
Use Below code into the button click.
Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class);
intent.putExtra("SCAN_MODE", "ONE_D_MODE");
intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE");
intent.setAction(Intents.Scan.ACTION);
startActivityForResult(intent, 1);
And override this method to get result of scanning.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final String contents = intent.getStringExtra(Intents.Scan.RESULT);
final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT);
}
}
in handleDecodeInternally you directly intent the Capture Activity to desired Activity
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
maybeSetClipboard(resultHandler);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (resultHandler.getDefaultButtonID() != null && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) {
resultHandler.handleButtonPress(resultHandler.getDefaultButtonID());
return;
}
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.GONE);
Intent intent = new Intent(CaptureActivity.this, AfterCaptureActivity.class);
startActivity(intent);
finish();
So lets say i have 4 buttons , and each button contains an intent which navigates to an activity.They all navigate to a single same activity . When i click the first button i want that new activity to show "Hi" , When i click the second button i want it to show "Bye" and so on . How do i do that ?
Here is a simple code to start with
public class Intentt extends Activity {
Button b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button)findViewById(R.id.button2);
b2 = (Button)findViewById(R.id.button3);
b3 = (Button)findViewById(R.id.button4);
b4 = (Button)findViewById(R.id.button5);
b1.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b2.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b3.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b4.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
}
Just pass some data through intent extras, or intent extra Bundle:
Intent i=new Intent(context,MainActivity.class);
i.putExtra(id, 453);
context.startActivity(i);
Example:
Button b1, b2, b3, b4;
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button) findViewById(R.id.button2);
b2 = (Button) findViewById(R.id.button3);
b3 = (Button) findViewById(R.id.button4);
b4 = (Button) findViewById(R.id.button5);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, MainActivity.class);
i.putExtra(MainActivity.ID_ACTION, MainActivity.ACTION_1);
startActivity(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, MainActivity.class);
i.putExtra(MainActivity.ID_ACTION, MainActivity.ACTION_2);
startActivity(i);
}
});
}
And then in that activity you can switch on that values getting them like that:
String id = intent.getStringExtra("id");
int id = intent.getIntExtra("id",-1);
and then use the if-elseif-else or switch statement(s) to change the actions based on the passed action, so you can display your messages
To properly recieve them you need to set activity's launchMode to "standard" because of this bug in AndroidManifest.xml and create
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int id = getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(MainActivity.this, "id is null!", Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(MainActivity.this, "Aloha from button 1!", Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(MainActivity.thi,"Hello from button 2!", Toast.LENGTH_LONG).show();
}
}
In each intent you could pass parameterts
Intent i=new Intent(context,SendMessage.class);
i.putExtra("KEY_MESSAGE", "Hola amigo");
In the other activity
Intent i = getIntent();
String message = i.getStringExtra("KEY_MESSAGE")
Toast.make(this,message,Toast.LENGTH_SHORT).show()
Re write the button click listener as follows :
b1.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Hi");
startActivity(i);
}
});
b2.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Hello");
startActivity(i);
}
});
b3.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Bye");
startActivity(i);
}
});
b4.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","See you");
startActivity(i);
}
});
In your MainActivity class onCreate Method, you can access the passed data by :
String passedData = getIntent().getStringExtra("Data");
you can use this passedData to display on screen.
Do it like this:
public class Intentt extends Activity implements View.OnClickListener {
Button b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button)findViewById(R.id.button2);
b2 = (Button)findViewById(R.id.button3);
b3 = (Button)findViewById(R.id.button4);
b4 = (Button)findViewById(R.id.button5);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button2:
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra('"STRING_I_NEED"', "Hi");
startActivity(i)
break;
case R.id.button3:
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra('"STRING_I_NEED"', "Bye");
startActivity(i)
break;
case R.id.button4:
break;
.
.
.
}
}
}
After that in your mainActivity retrieve string that you sent with:
Bundle extras = getIntent().getExtras();
String s = extras.getString("STRING_I_NEED");
I been working on Android Native App , What i was trying to do is :
Activities - A -> B -> C Then A-> B -> C -> C .
From C Activity if it again point to C then i want to remove C , B from stack manually .
On my back it should move only to A .
I tried finish() but problem is :
Activities - A -> B -> C Then A-> B -> C -> C on finish A -> B -> C required state A-> C .
Is anyone know how to catch all activities in stack and remove specific activities from stack ??
In Activity C, override onBackPressed and add in something like:
#Override
public void onBackPressed() {
if (shouldGoBackToA) { // There are various ways this could be set
Intent intent = new Intent(this, AActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
finish();
}
}
FLAG_ACTIVITY_CLEAR_TOP will cause it to go down the stack to the existing copy of A Activity instead of starting a new one. From the docs:
public static final int FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
While calling intent pass a flag called actvity clear top like this:
Intent newIntent=new Intent(this,MainActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(newIntent);
You can use this :
In A activity while passing to B activity, the intent should be added with a flag FLAG_ACTIVITY_NO_HISTORY like this,
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent=new Intent(AActivity.this,Bactivty.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(newIntent);
}
});
While moving to CActivity:
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent = new Intent(Bactivty.this, CActivity.class);
startActivity(newIntent);
}
});
On backpress will take you to AActivity now.
Step 1: Start activty for result A -> B -> C1 -> C2..
Call your Activity with startActivityForResult
Intent intent = new Intent(yourActivity.this, nextActivity.class);
startActivityForResult(intent, 1);
Step 2: In C2 specify that you want to go back to A..
Whenever you are done with your activity write the below code
Intent i = getIntent();
i.putString("Result","GottoA");
setResult(Activity.RESULT_OK, i);
finish();
Step 3: Whenever C2 finishes , previsus stack activit's onActivityResult is called.. so u can check in C1 and B onActivityResult whether you have set any result bck.. and finish accordingly
and impliment the following code in Activity B and c
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Intent i = getIntent();
if (resultCode == RESULT_OK && i.getString("Result","null").equals"GottoA") {
i.putString("Result","GottoA");
setResult(RESULT_OK, i);
finish();
}
}
In Activity C, when back button is pushed start activity A like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), A.class);
intent.putExtra("EXIT", true);
startActivity(intent);
}
Then in Activity A's onCreate() do this
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
this complete example may help you...
public class ActivityA extends Activity {
public static final int ID_TEXTVIEW = 0xDEAF1;
public static final int ID_BUTTON = 0xDEAF2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = getContentView(this);
TextView textView = (TextView) contentView.findViewById(ID_TEXTVIEW);
textView.setText("ActivityA");
setContentView(contentView);
final Button button = (Button) contentView.findViewById(ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
}
});
}
public static View getContentView(Context context) {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
TextView textView = new TextView(context);
textView.setLayoutParams(layoutParams);
textView.setId(ID_TEXTVIEW);
layout.addView(textView);
Button button = new Button(context);
button.setText("Next");
button.setLayoutParams(layoutParams);
button.setId(ID_BUTTON);
layout.addView(button);
return layout;
}
}
public class ActivityB extends Activity {
public static final String ACTION_FINISH = "com.myapp.test2.ACTION_FINISH";
public ActivityB() {
}
private FinishReceiver finishReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = ActivityA.getContentView(this);
final TextView textView = (TextView) contentView
.findViewById(ActivityA.ID_TEXTVIEW);
textView.setText("ActivityB");
setContentView(contentView);
final Button button = (Button) contentView
.findViewById(ActivityA.ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityB.this, ActivityC.class);
startActivity(intent);
}
});
finishReceiver = new FinishReceiver();
IntentFilter filter = new IntentFilter(ACTION_FINISH);
registerReceiver(finishReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(finishReceiver);
}
private class FinishReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_FINISH)) {
finish();
}
}
}
}
public class ActivityC extends Activity {
public ActivityC() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = ActivityA.getContentView(this);
final TextView textView = (TextView) contentView
.findViewById(ActivityA.ID_TEXTVIEW);
textView.setText("ActivityC");
setContentView(contentView);
final Button button = (Button) contentView.findViewById(ActivityA.ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityB.ACTION_FINISH);
sendBroadcast(intent);
intent = new Intent(ActivityC.this, ActivityC.class);
startActivity(intent);
finish();
}
});
}
}
I'm newbie in android, and i'm trying to receive a variable through the Intent function, and according the and depending on the value of the variable is supposed to show a contentview.
Bundle parametros = getIntent().getExtras();
String type = parametros.getString("tipo");
int accao = parametros.getInt("accao");
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (type=="medicamentos") {
Button voltar = (Button) findViewById(R.id.button1);
voltar.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent medIntent = new Intent(view.getContext(), Listar.class);
startActivityForResult(medIntent, 0);
}
});
if (accao==1)
setContentView(R.layout.adicionar_medicamentos);
if (accao==2)
setContentView(R.layout.editar_medicamentos);
}
}
What i'm doing wrong? Thanks
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String type = getIntent().getString("tipo");
int accao = getIntent().getInt("accao");
if (type != null && type.equals("medicamentos")) {
Button voltar = (Button) findViewById(R.id.button1);
voltar.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent medIntent = new Intent(view.getContext(), Listar.class);
startActivityForResult(medIntent, 0);
}
});
if (accao==1)
setContentView(R.layout.adicionar_medicamentos);
if (accao==2)
setContentView(R.layout.editar_medicamentos);
}
}
Use equals() to compare the string.
== compares the Object references not their content.
if(type.equals("medicamentos")) {
....
}
I am having trouble passing data read from a text file to another class in the app. I can read from the file just fine, but I think I need to use Bundle, but I'm not sure how to do it. I would like to have the second class handle the data from the text file, and then display it in the first class.
Edit: I've figured out how to pass the string from the file using an intent. I'm still working on getting some of the bugs out.
2nd Edit: I know there is a more efficient way of doing this. The only way I can get it to work is to have the first button in MainActivity use startActivity(intent) to allow secondActivity to bundle the string read from the file.
MainActivity.java:
public class MainActivity extends Activity {
Button btn;
Button bReadFile;
TextView tvRead;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btnNext);
bReadFile = (Button) findViewById(R.id.btnRead);
tvRead = (TextView) findViewById(R.id.tvMain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//trying to find a way to remove this button
Intent intent = new Intent(MainActivity.this, econdActivity.class);
startActivity(intent);
}
});
bReadFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String value = getIntent().getExtras().getString("key");
tvRead.setText(value);
}
});
}
}
secondActivity.java:
public class secondActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent mIntent = new Intent(secondActivity.this, MainActivity.class);
mIntent.putExtra("key", readDataFile());
startActivity(mIntent);
}
public String readDataFile() {
String strData = null;
InputStream is = null;
try {
is = getResources().openRawResource(R.raw.data_text);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
strData = br.readLine();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return strData;
}
}
Use the below edited code for your requirement
MainActivity.java
public class MainActivity extends Activity {
Button btn;
Button bReadFile;
TextView tvRead;
String value;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btnNext);
bReadFile = (Button) findViewById(R.id.btnRead);
tvRead = (TextView) findViewById(R.id.tvMain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//trying to find a way to remove this button
Intent intent = new Intent(MainActivity.this, secondActivity.class);
startActivityForResults(intent,0);
}
});
bReadFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tvRead.setText(value);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
value = data.getStringExtra("key");
}
}
the code for secondActivity.java
public class secondActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent();
i.putExtra("key", readDataFile());
setResult(RESULT_OK, i);
finish();
}
public String readDataFile() {
String strData = null;
InputStream is = null;
try {
is = getResources().openRawResource(R.raw.data_text);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
strData = br.readLine();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return strData;
}
}