Changing menuitem on returning from activity - java

I want to change the menuitem register of my menu when I return from another activity to settings which will go to a new intent. On clicking register which is in menu_item the activity goes to RegisterActivity. On returning from RegisterActivity I want to change the menu item register to settings.
package com.mausamakasvani.srsk.mausamakasvani;
public class LoginActivity extends AppCompatActivity {
private EditText password;
private EditText userName;
public static boolean Register;
public static final int REG_REQ_CODE = 235;
private int x = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar as = getSupportActionBar();
as.setTitle("Login");
userName = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
}
public void onLoginClicked(View view){
/*
*/
if (!MausamCheckList.getStringValue(this,MausamCheckList.USER_NAME).equals(MausamCheckList.DEF_VALUE)) {
if (userName.getText().toString().equals(MausamCheckList.getStringValue(this, MausamCheckList.USER_NAME)) && password.getText().toString().equals(MausamCheckList.getStringValue(this, MausamCheckList.PASSWORD))) {
Intent intent = new Intent(this,SheharChunoActivity.class);
startActivity(intent);
//finish();
}else {
MausamCheckList.displayToast(this,"Username or Password is Wrong!!!");
}
}else{
MausamCheckList.displayToast(this,"Please register");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
if(x==0)
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Intent intent = new Intent(this,RegisterActivity.class);
startActivityForResult(intent,REG_REQ_CODE);
//startActivity(intent);
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REG_REQ_CODE) {
if (resultCode == RegisterActivity.REG_RES_CODE) {
x=RegisterActivity.REG_RES_CODE;
}
}
}
}

You can include both menu items in one menu.xml file and depending on what you want to show change visibility of particular item. You can simple hold reference to Menu (and use findItem method as well) or MenuItem inside your activity and manage it like this (pseudo-code):
if(user.isRegistered()) {
mSettingsMenuItem.setVisibility(View.VISIBLE);
mRegisterMenuItem.setVisibility(View.GONE);
}
You can also use
public boolean onPrepareOptionsMenu (Menu menu)
which is called everytime menu is shown on the screen and depending on the conditions show proper menu items
Documentation for this

Related

Displaying data in main Activity from two other Activities

I'm very new to Android Studio. I am trying to get data from my EditMessage and EditSendTo activities to my TestExplicitIntents activity. This is a school project, but all I was required to do was create the EditSendTo activity and display the phone number in the TestExplicitIntents activity.
I can do this following lessons on the other activities, but I would like to learn how to display the data from both Edit activities. I have tried several approaches but everything I try ends with either the EditMessage or the EditSendTo producing null results once the Done button is pressed.
public class TestExplicitIntents extends Activity {
public static final String CLASS_TAG = "TestExplicitIntents";
public static final int NEW_MESSAGE_REQUEST = 1;
public static final int NEW_PHONE_REQUEST = 1;
private String message = "";
private String phone = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_explicit_intents);
// Getting to the views defined in the XML files.
TextView tvMessageDetails = (TextView) findViewById(R.id.tvMessageDetails);
tvMessageDetails.setBackgroundColor(Color.GREEN);
tvMessageDetails.setMovementMethod(new ScrollingMovementMethod());
message ="Is it St. Patricks Day?";
phone = "";
setSummary();
// Responding to an event - the onClick for the Edit Message Button
// Using a named inner class
Button btnEditMessage;
btnEditMessage = (Button) this.findViewById(R.id.btnEditMessage);
HandleButtonEditMessageOnClick buttonEditMessageOnClick;
buttonEditMessageOnClick = new HandleButtonEditMessageOnClick();
btnEditMessage.setOnClickListener(buttonEditMessageOnClick);
// Responding to an event - the onClick for the Edit Send To Button
// Using a named inner class
Button btnEditSendTo;
btnEditSendTo = (Button) this.findViewById(R.id.btnEditSendTo);
HandleButtonEditSendToOnClick buttonEditSendToOnClick;
buttonEditSendToOnClick = new HandleButtonEditSendToOnClick();
btnEditSendTo.setOnClickListener(buttonEditSendToOnClick);
}
/**
* Put together a summary of the phone and message and display it.
*/
private void setSummary() {
StringBuilder summary;
summary = new StringBuilder("Sending To:\n");
summary.append(phone);
summary.append("\n\nMessage:\n");
summary.append(message);
TextView tvMessageDetails = (TextView) findViewById(R.id.tvMessageDetails);
tvMessageDetails.setText(summary);
}
/**
* Handle Edit Button OnClick by starting the activity This is an example of
* starting another activity using an explicit Intent.
*
*/
#SuppressWarnings("rawtypes")
public class HandleButtonEditMessageOnClick implements OnClickListener {
public static final String CLASS_TAG = "HandleButtonEditMessageOnClick";
public void onClick(View v) {
Log.i(CLASS_TAG, "onClick started...");
// Example of an EXPLICIT intent, as we are naming the java class to use
// (EditMessage.class)
Intent editIntent;
Activity sourceActivity;
Class destinationClass;
sourceActivity = TestExplicitIntents.this;
destinationClass = EditMessage.class;
editIntent = new Intent(sourceActivity, destinationClass);
// Sending information to the intent receiver through the Intent object
editIntent.putExtra("CURRENT_MESSAGE", TestExplicitIntents.this.message);
//startActivity(editIntent);
startActivityForResult(editIntent, NEW_MESSAGE_REQUEST);
}
}
#SuppressWarnings("rawtypes")
public class HandleButtonEditSendToOnClick implements OnClickListener {
public static final String CLASS_TAG = "HandleButtonEditSendToOnClick";
public void onClick(View v) {
Log.i(CLASS_TAG, "onClick started...");
Intent editSendIntent;
Activity startActivity;
Class endClass;
startActivity = TestExplicitIntents.this;
endClass = EditSendTo.class;
editSendIntent = new Intent(startActivity, endClass);
// Sending information to the intent receiver through the Intent object
editSendIntent.putExtra("CURRENT_PHONE", TestExplicitIntents.this.phone);
//startActivity(editIntent);
startActivityForResult(editSendIntent, NEW_PHONE_REQUEST);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
String newMessage = getIntent().getStringExtra("NEW_MESSAGE");
String curMessage = getIntent().getStringExtra("CURRENT_MESSAGE");
String newPhone = getIntent().getStringExtra("NEW_PHONE");
String curPhone = getIntent().getStringExtra("CURRENT_PHONE");
// Check which request we're responding to
if (requestCode == NEW_MESSAGE_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
message = newMessage;
phone = curPhone;
setSummary();
}
}
if (requestCode == NEW_PHONE_REQUEST) {
if (resultCode == RESULT_OK) {
message = curMessage;
phone = newPhone;
setSummary();
}
}
}
}
Here is EditMessage:
public class EditMessage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_message);
// Get the intent for this activity. Every activity has an intent and
// set the EditText contents to the string in the extra info that comes with
// the intent
Intent editIntent;
EditText etMessage;
editIntent = this.getIntent();
String theMessage;
theMessage = editIntent.getStringExtra("CURRENT_MESSAGE");
etMessage = (EditText) this.findViewById(R.id.etMessage);
etMessage.setText(theMessage);
// Get an event handler going for the Done button so that we can return the
// new message
Button btnDone = (Button) this.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new ButtonDoneOnClickHandler());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_message, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Handles the Button Done onClick event by creating a resulting Intent and
* finishing
*/
private class ButtonDoneOnClickHandler implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NEW_MESSAGE", ((EditText) findViewById(R.id.etMessage)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
}
Here is EditSendTo:
public class EditSendTo extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_send_to);
// Get the intent for this activity. Every activity has an intent and
// set the EditText contents to the string in the extra info that comes with
// the intent
Intent editIntent;
EditText etPhone;
editIntent = this.getIntent();
String thePhone;
thePhone = editIntent.getStringExtra("CURRENT_PHONE");
etPhone = (EditText) this.findViewById(R.id.etPhone);
etPhone.setText(thePhone);
// Get an event handler going for the Done button so that we can return the
// new message
Button btnDone = (Button) this.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new ButtonDoneOnClickHandler());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_send_to, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Handles the Button Done onClick event by creating a resulting Intent and
* finishing
*/
private class ButtonDoneOnClickHandler implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NEW_PHONE", ((EditText)
findViewById(R.id.etPhone)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
}
I tried to figure this out for a few days and have had no luck finding an answer.
I would really appreciate a pointer in the right direction.
Your code should be like below :
TestExplicitIntents.java
public class TestExplicitIntents extends Activity {
public static final String CLASS_TAG = "TestExplicitIntents";
public static final int NEW_MESSAGE_REQUEST = 1;
public static final int NEW_PHONE_REQUEST = 2;
private String message = "";
private String phone = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_explicit_intents);
// Getting to the views defined in the XML files.
TextView tvMessageDetails = (TextView) findViewById(R.id.tvMessageDetails);
tvMessageDetails.setBackgroundColor(Color.GREEN);
tvMessageDetails.setMovementMethod(new ScrollingMovementMethod());
message = "Is it St. Patricks Day?";
phone = "";
setSummary();
// Responding to an event - the onClick for the Edit Message Button
// Using a named inner class
Button btnEditMessage;
btnEditMessage = (Button) this.findViewById(R.id.btnEditMessage);
HandleButtonEditMessageOnClick buttonEditMessageOnClick;
buttonEditMessageOnClick = new HandleButtonEditMessageOnClick();
btnEditMessage.setOnClickListener(buttonEditMessageOnClick);
// Responding to an event - the onClick for the Edit Send To Button
// Using a named inner class
Button btnEditSendTo;
btnEditSendTo = (Button) this.findViewById(R.id.btnEditSendTo);
HandleButtonEditSendToOnClick buttonEditSendToOnClick;
buttonEditSendToOnClick = new HandleButtonEditSendToOnClick();
btnEditSendTo.setOnClickListener(buttonEditSendToOnClick);
}
/**
* Put together a summary of the phone and message and display it.
*/
private void setSummary() {
StringBuilder summary;
summary = new StringBuilder("Sending To:\n");
summary.append(phone);
summary.append("\n\nMessage:\n");
summary.append(message);
TextView tvMessageDetails = (TextView) findViewById(R.id.tvMessageDetails);
tvMessageDetails.setText(summary);
}
/**
* Handle Edit Button OnClick by starting the activity This is an example of
* starting another activity using an explicit Intent.
*/
#SuppressWarnings("rawtypes")
public class HandleButtonEditMessageOnClick implements View.OnClickListener {
public static final String CLASS_TAG = "HandleButtonEditMessageOnClick";
public void onClick(View v) {
Log.i(CLASS_TAG, "onClick started...");
// Example of an EXPLICIT intent, as we are naming the java class to use
// (EditMessage.class)
Intent editIntent;
Activity sourceActivity;
Class destinationClass;
sourceActivity = TestExplicitIntents.this;
destinationClass = EditMessage.class;
editIntent = new Intent(sourceActivity, destinationClass);
// Sending information to the intent receiver through the Intent object
editIntent.putExtra("CURRENT_MESSAGE", TestExplicitIntents.this.message);
//startActivity(editIntent);
startActivityForResult(editIntent, NEW_MESSAGE_REQUEST);
}
}
#SuppressWarnings("rawtypes")
public class HandleButtonEditSendToOnClick implements View.OnClickListener {
public static final String CLASS_TAG = "HandleButtonEditSendToOnClick";
public void onClick(View v) {
Log.i(CLASS_TAG, "onClick started...");
Intent editSendIntent;
Activity startActivity;
Class endClass;
startActivity = TestExplicitIntents.this;
endClass = EditSendTo.class;
editSendIntent = new Intent(startActivity, endClass);
// Sending information to the intent receiver through the Intent object
editSendIntent.putExtra("CURRENT_PHONE", TestExplicitIntents.this.phone);
//startActivity(editIntent);
startActivityForResult(editSendIntent, NEW_PHONE_REQUEST);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check which request we're responding to
if (requestCode == NEW_MESSAGE_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
message = data.getStringExtra("NEW_MESSAGE");
setSummary();
}
} else if (requestCode == NEW_PHONE_REQUEST) {
if (resultCode == RESULT_OK) {
phone = data.getStringExtra("NEW_PHONE");
setSummary();
}
}
}
}
EditSendTo class:
public class extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_send_to);
// Get the intent for this activity. Every activity has an intent and
// set the EditText contents to the string in the extra info that comes with
// the intent
Intent editIntent;
EditText etPhone;
editIntent = this.getIntent();
String thePhone;
thePhone = editIntent.getStringExtra("CURRENT_PHONE");
etPhone = (EditText) this.findViewById(R.id.etPhone);
etPhone.setText(thePhone);
// Get an event handler going for the Done button so that we can return the
// new message
Button btnDone = (Button) this.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new ButtonDoneOnClickHandler());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_edit_send_to, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Handles the Button Done onClick event by creating a resulting Intent and
* finishing
*/
private class ButtonDoneOnClickHandler implements View.OnClickListener {
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NEW_PHONE", ((EditText)
findViewById(R.id.etPhone)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
}
EditMessage class:
public class EditMessage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_message);
// Get the intent for this activity. Every activity has an intent and
// set the EditText contents to the string in the extra info that comes with
// the intent
Intent editIntent;
EditText etMessage;
editIntent = this.getIntent();
String theMessage;
theMessage = editIntent.getStringExtra("CURRENT_MESSAGE");
etMessage = (EditText) this.findViewById(R.id.etMessage);
etMessage.setText(theMessage);
// Get an event handler going for the Done button so that we can return the
// new message
Button btnDone = (Button) this.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new ButtonDoneOnClickHandler());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_edit_message, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Handles the Button Done onClick event by creating a resulting Intent and
* finishing
*/
private class ButtonDoneOnClickHandler implements View.OnClickListener {
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NEW_MESSAGE", ((EditText) findViewById(R.id.etMessage)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
}

Why is my StringSet not saved to SharedPreferences?

I'm building an app that uses Google Places Api. Right now, when the user picks a place, the place name is added to a StringSet, which is then (supposed to be) saved to SharedPreferences. However, every time I restart the app, SharedPreferences is cleared. How do I fix this?
public class MainActivity extends AppCompatActivity {
PlacePicker.IntentBuilder builder;
int PLACE_PICKER_REQUEST;
ListView placeListView;
ArrayList<String> placeArrayList;
ArrayAdapter<String> arrayAdapter;
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
placeListView = (ListView) findViewById(R.id.placeListView);
placeArrayList = new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, placeArrayList);
placeListView.setAdapter(arrayAdapter);
sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLACE_PICKER_REQUEST = 1;
builder = new PlacePicker.IntentBuilder();
pickPlace();
}
});
}
public void pickPlace(){
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
placeArrayList.add((String) place.getName());
arrayAdapter.notifyDataSetChanged();
Set<String> set = new HashSet<String>();
set.addAll(placeArrayList);
editor.putStringSet("key", set);
sharedPreferences.edit().putStringSet("key", set).apply();
Log.e("places", String.valueOf(sharedPreferences.getStringSet("key", null)));
//Retrieve the values
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

com.google.zxing.client.android.result return a Null pointer exception

i am trying to develop a simple app that read a QR code with zxing and redirect to the corresponding link. I do the MainActivity Class, with methods on create and onActivityResult, but when i scan a QR code my app crashes....and i dunno why can anyone help me? i post my MainActivity class, if it can help...
Thanks to all
Fabrizio
-------- MainActivity------------
public class MainActivity extends Activity {
// static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
private Button button;
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Context context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.go_direct);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, WebViewActivity.class);
startActivity(intent);
}
});
}
public void scanNow(View view) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
// intent.setPackage("com.google.zxing.client.android");
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE",
"QR_CODE_MODE");
startActivityForResult(intent, 0);
}
#SuppressLint("SetJavaScriptEnabled")
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
Log.i("intent", intent.toString());
Log.i("scan result", intent.getStringExtra("SCAN_RESULT"));
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Log.i("xZing", "contents: " + contents + " format: " + format); // Handle
// successful
// scan
setContentView( R.layout.web_view);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(contents);
} else if (resultCode == RESULT_CANCELED) { // Handle cancel
Log.i("xZing", "Cancelled");
}
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);}}

Android: button does not work

So there is 4 buttons on this page... 3 of them work fine, the 4th button, which links to ToolsTableLayout.class does not respond at all. There are no erros, the app does not crash or anything... you just click the button and nothing happens.
Code for the button class:
public class MainMenu extends Activity implements OnClickListener{
private String result;
boolean isScanout;
public static final String SCAN_RESULT = "MyPreferencesFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
Button ScanOut=(Button)findViewById(R.id.scanout);
ScanOut.setOnClickListener(this);
Button ScanIn=(Button)findViewById(R.id.scanin);
ScanIn.setOnClickListener(this);
Button EndSession = (Button) findViewById(R.id.endsession);
EndSession.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.scanout){
isScanout = true;
IntentIntegrator.initiateScan(this);
}
else if(v.getId()==R.id.scanin){
isScanout = false;
IntentIntegrator.initiateScan(this);
}
else if(v.getId()==R.id.endsession){
Intent endsessionintent = new Intent(MainMenu.this, MainActivity.class);
startActivity(endsessionintent);
}
else if(v.getId()==R.id.toolDB){
Intent i = new Intent(MainMenu.this, ToolsTableLayout.class);
startActivity(i);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case IntentIntegrator.REQUEST_CODE: {
if (resultCode != RESULT_CANCELED) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult != null) {
String qrCode = scanResult.getContents();
SharedPreferences codeHack = getSharedPreferences(SCAN_RESULT,0);
SharedPreferences.Editor editor = codeHack.edit();
editor.putString("entry", qrCode);
editor.commit();
}
}
}
}
}
#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;
}
}
R.id.toolDB is the button that makes no response..
and here is the ToolsTableLayout.java class (which does not open):
public class ToolsTableLayout extends Activity {
public static final String SCAN_RESULT = "MyPreferencesFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablelayout2);
SharedPreferences codeHack = getSharedPreferences(SCAN_RESULT,0);
String QRcode = codeHack.getString("entry", "unregistered");
StringTokenizer token = new StringTokenizer(QRcode," ");
String name = token.nextToken();
String quantity = token.nextToken();
TextView t1 = (TextView) findViewById(R.id.slot1b);
TextView t2 = (TextView) findViewById(R.id.slot2b);
TextView t3 = (TextView) findViewById(R.id.slot3b);
ToolDB info = new ToolDB(this);
info.open();
String c1 = info.getRowID();
info.createEntry(name, quantity);
info.close();
t1.setGravity(Gravity.CENTER_HORIZONTAL);
t2.setGravity(Gravity.CENTER_HORIZONTAL);
t3.setGravity(Gravity.CENTER_HORIZONTAL);
t1.setText(c1);
t2.setText(name);
t3.setText(quantity);
}
}
not sure if the XML files are needed? if so let me know and I will update.
You did not set onClickListener for 4th button. Please add
Button btnToolDb = (Button) findViewById(R.id.toolDB);
btnToolDb.setOnClickListener(this);
Judging by the code you have provided, I believe you have forgotten to create and attach the ClickListener to the fourth button which is missing from the code.

Returning Data Result to Parent Activity using Intents

I am able to successfully transfer the string in my ListView in my first Activity to the EditText in my second Activity. I now want to edit the text and send it back to update my ListView in my first Activity. I basically want to have the edits be sent back to the first activity as a popup to help me test which string is being passed back
I'm not sure what Intent to put in my onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
Here is my first Activity:
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
private final int REQUEST_CODE = 20;
//private Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
onActivityResult(REQUEST_CODE, RESULT_OK, /** Intent variable **/);
}
private void launchEditItem(String item) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", item); // list item into edit text
//startActivityForResult(i, REQUEST_CODE);
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
String text = (String) lvItems.getItemAtPosition(pos);
launchEditItem(text);
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String name = data.getExtras().getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
}
}
I thought about using the Intent from the second activity but I'm not sure how to do so.
Here is my second Activity.
public class EditItemActivity extends Activity {
private EditText etEditItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
etEditItem = (EditText)findViewById(R.id.etEditItem);
etEditItem.setText(ItemToEdit);
onSubmit(etEditItem);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_item, menu);
return true;
}
public void DoneEdit(View v) {
this.finish();
}
public void onSubmit(View v) {
EditText etName = (EditText) findViewById(R.id.etEditItem);
Intent data = new Intent();
data.putExtra("EditedItem", etName.getText().toString());
setResult(RESULT_OK, data);
finish();
}
}
To get result form an activity (child) you do as follow :
In the parent activity
startActivityForResult(myIntent, 1);
global vars of your parent activity
boolean backFromChild = false;
String aString;
then still in the parent activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// code for result
aString = getIntent().getExtras().getString("aString");
backFromChild = true;
}
if (resultCode == RESULT_CANCELED) {
// Write your code on no result return
}
}
}
in your child you do somewhere something like that
Intent returnIntent = new Intent();
//example of sending back a string to the parent.
returnIntent.putExtra("aString", aString);
setResult(RESULT_OK, returnIntent);
finish();
The thing is that onResume of your parent activity will be called when returning from your child. In there you have to perform the update, in your case it is to update the information of the edited text :
#Override
public void onResume(){
super.onResume();
if (backFromChild){
backFromChild = false;
//do something with aString here
Toast.makeText(this, aString, Toast.LENGTH_SHORT).show();
}
}
Basically, in the onActivityResult I get the info back from the intent of the child. Then in onResume I use this info.
For your concern you can utilize SharedPreferences
For ex: Put data in SP in second activity like this
SharedPreferences spppp = getSharedPreferences("tab", 0);
SharedPreferences.Editor editors = spppp.edit();
editors.putString("for", "0");
editors.commit();
and fetch data for list view in first activity like this
SharedPreferences spppp = getSharedPreferences("tab", 0);
String your_list_view_value = spppp.getString("for", "");

Categories