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.
Related
Problem: I cannot pass the rating value/data from the rating bar to another intent. It only shows me this instead of the value/data from the rating bar.
Rating: MainActivity#79b604
I think the error is that it did not properly get the value from the rating bar or it did not pass the value correctly. Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
String rating_float = "0.0";
private TextView txtRatingValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rating_float = String.valueOf(rating);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = getApplicationContext();
CharSequence text = "";
Intent intent_rating = new Intent(this, SecondActivity.class);
intent_rating.putExtra("rating_float", toString());
startActivity(intent_rating);
return super.onOptionsItemSelected(item);
}}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView Msg;
String PassedValue = null;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
PassedValue = getIntent().getStringExtra("rating_float");
Msg = (TextView) findViewById(R.id.Msg);
Msg.setText("Dimension: 479\nFormat: JPEG\nSize: 360x360\nRating: " + PassedValue);
}
Questions:
Am I doing the right way on getting the value for the rating bar?
How to pass the value/data from the rating bar into the next activity/intent and how to get it from the SecondActivity.java?
That is because you pass the result of MainActivity.toString() to your second activity
Instead of
intent_rating.putExtra("rating_float", toString());
you should presumably write
intent_rating.putExtra("rating_float", this.rating_float);
You are receiving it well but not sending what you have to.
Just use this:
intent_rating.putExtra("rating_float", rating_float);
First you need to save your value into the putExtra of the intent you use to go to the another activity
intent_rating.putExtra("rating_float", rating_float);
to get the value in the SecondActivity you just need to do this wherever you need the value.
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String rating_value =(String) b.get("rating_float");
}
Simple and Clear Solution
//1stActivity
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float rating = rate.getRating();
Intent intent = new Intent(ContactActivity.this,RatingIntentSOF.class);
Bundle bundle = new Bundle();
bundle.putFloat("totalRating",rating);
intent.putExtras(bundle);
startActivity(intent);
//2nd Activity, get the data of 1st Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating_intent_sof);
TextView textView = (TextView) findViewById(R.id.text);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
float totalRating = bundle.getFloat("totalRating");
textView.setText(String.valueOf(totalRating));
}
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();
}
}
}
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);}}
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", "");
Im new at android development. I'm developing an app where first of all, I have a main activity where I must turn On/Off the bluetooth, make it discoverable, search devices and connect to them.
After this, I go to other activity where I have a text view with a edittext and a send button, where I can write something and send it.
I've got working all the bluetooth enabling/disabling stuff, but now I need to connect to new found devices and then enter to the chat type activity and send.
I now this is pretty much work, but it would be great if you can give me an example of how can I do this. This is the code i have:
public class BTActivity extends Activity {
// Intent request codes
private static final int REQUEST_DISCOVERABLE_BT = 0;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Name of the connected device
public static String mConnectedDeviceName = null;
// Array adapter for device list
private ArrayAdapter<String> mArrayAdapter;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button1 = (Button) findViewById(R.id.boton1);
final Button button2 = (Button) findViewById(R.id.boton2);
final Button button3 = (Button) findViewById(R.id.boton3);
final Button button4 = (Button) findViewById(R.id.boton4);
final Button button5 = (Button) findViewById(R.id.boton5);
button5.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
lanzarComunicacion (null);
}
});
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
button3.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);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//LLAMA A LA DIALOG ACTIVITY PARA VISUALIZAR LOS DISPOSITIVOS
LanzarBusqueda(null);
}
});
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
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 discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
});
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mBluetoothAdapter.disable();
Context context = getApplicationContext();
CharSequence text = "TURNING_OFF BLUETOOTH";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, 15);
toast.show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
connectDevice(data);
}
}
}
private void connectDevice(Intent data) {
String address = data.getExtras().getString(DeviceListDialog.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BTCommunication.mChatService.connect(device);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bt, menu);
return true;
}
public void lanzarComunicacion (View view) {
Intent i = new Intent(this, BTCommunication.class);
startActivity(i);
}
public void LanzarBusqueda (View view) {
Intent i = new Intent(this, DeviceListDialog.class);
startActivity(i);
}
}