I have the following situation:
I have two activities (Main Activity and ProductCard Activity)
Main Activity has a RecyclerView with items in it.
( User can add items manually. For example he add 3 items)
User click on some item and go to the ProductCard Activity
In the ProductCard Activity user click on the button (moneyOk_readylist) and go to the Main Activity
But when User do last step, RecyclerView become blank (empty).
I know that it is connected with states, but doesn't understand how.
Can anyone help me?
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Person> persons;
private RecyclerView rv;
final String LOG_TAG = "myLogs";
RVAdapter adapter;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
rv = (RecyclerView)findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
persons = new ArrayList<>();
adapter = new RVAdapter(persons);
rv.setAdapter(adapter);
if ((savedInstanceState != null) && (savedInstanceState.getSerializable("card") != null)) {
persons.clear();
persons.addAll((List<Person>) savedInstanceState.getSerializable("card"));
adapter.notifyDataSetChanged();
Log.d(LOG_TAG, "restore card with persons" + persons);
}
adapter.setOnItemClickListener(new RVAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Toast.makeText(MainActivity.this, "push on item" + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, ProductCard.class);
startActivity(intent);
Log.d(LOG_TAG, "go to ProductCard class" + persons);
}
});
adapter.setOnItemLongClickListener(new RVAdapter.MyLongClickListener() {
#Override
public void onItemLongClick(int position, View v) {
Toast.makeText(MainActivity.this, "push on item long" + position, Toast.LENGTH_SHORT).show();
Log.d(LOG_TAG, "Removed " + position);
persons.remove(position);
adapter.notifyDataSetChanged();
}
});
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
person= new Person("Emma Wilson", "23 years old", R.drawable.im_beach);
persons.add(person);
Log.d(LOG_TAG, "push add" + persons);
adapter.notifyDataSetChanged();
}
});
}
#Override
protected void onResume() {
super.onResume();
adapter = new RVAdapter(persons);
rv.setAdapter(adapter);
Log.d(LOG_TAG, "onresume" + persons);
}
#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 void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("card", (Serializable) persons);
Log.d(LOG_TAG, "save cards" + persons);
}
#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);
}
}
ProductCard Activity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
/**
* Created by Dmitry on 01.11.2015.
*/
public class ProductCard extends AppCompatActivity implements AdapterView.OnItemClickListener {
final String LOG_TAG = "myLogs";
Button moneyOk_readylist;
ImageButton addPhoto;
ImageView imageView;
private static int LOAD_IMAGE_RESULTS = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_card);
moneyOk_readylist=(Button)findViewById(R.id.moneyOk_readylist);
addPhoto=(ImageButton)findViewById(R.id.add_photo);
imageView=(ImageView)findViewById(R.id.imageView);
addPhoto.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
addPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.setType("image/*");
//i.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(i,"Select picture"),1);
}
});
moneyOk_readylist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(ProductCard.this,MainActivity.class);
startActivity(intent);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
imageView.setImageURI(data.getData());
}
}
#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();
switch (id) {
case R.id.action_save_card:
Toast.makeText(ProductCard.this, "Карточка сохранена", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(ProductCard.this,MainActivity.class);
startActivity(intent);
Log.d(LOG_TAG, "go to Main class" );
break;
case R.id.action_delete_card:
Toast.makeText(ProductCard.this, "Карточка удалена", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
Related
Unfortunately I have been banging my head against the wall for quite some time trying to figure out why the app crashes every time I press the "Display" button. As you can see an intent is called when the button is pressed, which should subsequently "change" to the GraphicDisplay Activity. Any help is appreciated.
package com.dwolford.app7;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Spinner;
public class Main extends Activity {
Button quit;
Button display;
String word;
EditText wordEntry;
PopupMenu popupMenu;
Button colorScheme;
Spinner spin;
Integer[] items = new Integer[51];
int spinnerValue = 90;//The current value of the spinner which is selected by the user
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int spinnerValues = 50;
spin = (Spinner) findViewById(R.id.spinner);
for(int i = 0; i < 51; i++)//Populate spinner with values from 50 to 100
{
items[i] = spinnerValues;
spinnerValues++;
}
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
spin.setAdapter(adapter);
spin.setSelection(40);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Creating popup menu on button click
colorScheme = (Button)findViewById(R.id.colorScheme);
colorScheme.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressLint("NewApi")
public void onClick(View v) {
popupMenu = new PopupMenu(Main.this, colorScheme);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.show();
}
});
wordEntry = (EditText)findViewById(R.id.word);
display = (Button)findViewById(R.id.display);
display.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
word = wordEntry.getText().toString();//Get word String
Intent intent = new Intent(Main.this, GraphicDisplay.class);
int scale = (Integer)spin.getSelectedItem();
String colorSchemeVal = popupMenu.toString();
//Pass Word, scale, and colorscheme using intent
intent.putExtra("colorSchemeVal", colorSchemeVal);//Pass current value for color scheme
intent.putExtra("scale", scale);//Pass scale to Graphic Activity
intent.putExtra("word", word);//Pass word to Graphic Activity via intent
startActivity(intent);
}
});
quit = (Button)findViewById(R.id.quit);
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#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);
}
}
I think I see your problem. You call inside display ClickListener:
String colorSchemeVal = popupMenu.toString();
but you never initialize "popupMenu", unless you hit "colorScheme".
I'm creating a simple note app in android. I am basically using two activity classes named as Main Page and Second Activity. I'm storing some data in the shared preferences in second activity and want to use it in my first Activity. I'm storing data in shared preferences as (String,Integer) key-pair. In my main activity class, when i'm getting the value from shared preferences as Integer and compare it with value 0,i'm getting an exception that java.lang.string can't be cast to java.lang.integer. I don't know why this exception is coming. Android studio is not giving me an exception but when i run my app, my app crashes. I have attach the code for reference.
MainActivity class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MainPage extends ActionBarActivity {
Notes notes = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
}
#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_page, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
//Map<String, Integer> notesMap = (Map<String, Integer>)sharedPreferences.getAll();
List<Notes> listNotes = new ArrayList<>();
Map<String, ?> prefsMap = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
if (entry.getValue() == 0){
notes = new Notes();
}
notes.setNoteText(entry.getKey());
listNotes.add(notes);
sharedPreferences.edit().putInt(entry.getKey(),2);
}
NotesArrayAdapter notesArrayAdapter = new NotesArrayAdapter(this,R.layout.list_layout, listNotes);
final ListView listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(notesArrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/**/
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
notes = (Notes) parent.getItemAtPosition(position);
Intent intent = new Intent(MainPage.this, SecondActivity.class);
intent.putExtra("Notes",notes);
startActivity(intent);
}
});
}
#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
switch (item.getItemId()) {
case R.id.new_link:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Notes",(android.os.Parcelable)null);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SecondActivity Class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class SecondActivity extends ActionBarActivity {
public SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
Notes notes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
edit = sharedPreferences.edit();
}
#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_second, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
notes = (Notes)intent.getParcelableExtra("Notes");
EditText editText = (EditText) findViewById(R.id.editText);
if(notes != null){
editText.setText(notes.getNoteText());
}
else{
editText.setText(null);
}
}
#Override
protected void onStop() {
super.onStop();
getIntent().removeExtra(notes.getNoteText());
}
#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();
Intent intent = getIntent();
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.save:
EditText editText = (EditText)findViewById(R.id.editText);
if (notes != null){
edit.putInt(String.valueOf(editText.getText()),1);
}
else{
edit.putInt(String.valueOf(editText.getText()),0);
}
edit.commit();
return true;
case R.id.delete:
if(notes != null){
edit.remove(notes.getNoteText());
edit.commit();
finish();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Notes class that I'm using:
package com.example.prateeksharma.noteballondor;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Dell on 02-06-2015.
*/
public class Notes implements Parcelable {
private String noteText;
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
private Notes(Parcel in) {
noteText = in.readString();
}
public Notes(){
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(noteText);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Notes> CREATOR = new Parcelable.Creator<Notes>() {
#Override
public Notes createFromParcel(Parcel in) {
return new Notes(in);
}
#Override
public Notes[] newArray(int size) {
return new Notes[size];
}
};
}
Can anybody tell me why this error is coming in MainActivity class at this line
if (entry.getValue() == 0)
Thank you..
Try to replace
if ((Integer)entry.getValue() == 0){
With
If((Integer.parseInt( entry.getValue()) ==0){
I'm learning android development. And I trying to do the following:
An wellcome activity, with a TextView with the following text: "Please Select"
This Textview, has an OnClick Listener setted.
My intent is, when the user click on this textview, one new activity with a listview must be opened.
This listview cointains some values like: Country 1, Country 2, Country 3 and so on;
So, when the user select one value, this value must be returned to the parent activity.
In my parent activity I have the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
countrySamples = (TextView)findViewById(R.id.countrySamples);
countrySamples.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListCountrySelectedFragment whatKindOjectIsThis = new ListCountrySelectedFragment();
whatKindOjectIsThis.setListCountrySelectedActivityDelegate(new ListCountrySelectedFragment.ListCountrySelectedActivityDelegate() {
#Override
public void selectCountry(String name) {
selectItem(name);
}
});
}
});
}
[...]
public void selectItem(String name) {
int index = valuesArray.indexOf(name);
if (index != -1) {
countryButton.setText(name);
}
}
And I've created an blank fragment with a list.
And added the following code:
public static interface ListCountrySelectedActivityDelegate {
public abstract void selectCountry(String name);
}
private ListCountrySelectedActivityDelegate delegate;
[...]
But, my fragment is never started.. The true is.. I have to create a Fragment to this? Or, must by an activity? Or I'm totally wrong?
Thanks
Edited (complete code):
Login Activity:
package com.testenum_13;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.testenum_13.R;
import com.testenum_13.adapters.CountryAdapter;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
public class Login extends ActionBarActivity {
TextView countryButton;
private EditText codeField;
private int countryState = 0;
private ArrayList<String> countriesArray = new ArrayList<String>();
private HashMap<String, String> countriesMap = new HashMap<String, String>();
private boolean ignoreOnTextChange = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
countryButton = (TextView)findViewById(R.id.countryButton);
countryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent intent = new Intent(Login.this, CountrySelected.class);
CountrySelected fragment = new CountrySelected();
fragment.setCountrySelectActivityDelegate (new CountrySelected.CountrySelectActivityDelegate() {
#Override
public void countryWSelected(String name) {
selectCountry(name);
}
});
//startActivity(intent);
}
});
}
#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_login, 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);
}
public void selectCountry(String name) {
int index = countriesArray.indexOf(name);
if (index != -1) {
ignoreOnTextChange = true;
codeField.setText(countriesMap.get(name));
countryButton.setText(name);
countryState = 0;
}
}
}
Country Activity:
package com.testenum_13;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.internal.widget.ActionBarOverlayLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.testenum_13.adapters.CountryAdapter;
import com.testenum_13.adapters.CountryAdapter.Country;
import java.util.List;
public class CountrySelected extends FragmentActivity {
public static interface CountrySelectActivityDelegate {
public abstract void countryWSelected(String name);
}
private CountryAdapter listViewAdapter;
private CountrySelectActivityDelegate delegate;
ListView countryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_selected);
countryList = (ListView)findViewById(R.id.countryList);
listViewAdapter = new CountryAdapter(getBaseContext());
countryList.setAdapter(listViewAdapter);
countryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Country country = null;
int section = listViewAdapter.getSectionForPosition(position);
int row = listViewAdapter.getPositionInSectionForPosition(position);
if (row < 0 || section < 0) {
return;
}
country = listViewAdapter.getItem(section, row);
if (position < 0) {
return;
}
if (country != null && delegate != null)
{
delegate.countryWSelected(country.name);
}
finish();
}
});
}
public void setCountrySelectActivityDelegate(CountrySelectActivityDelegate delegate) {
this.delegate = delegate;
}
#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_country_selected, 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);
}
}
Thanks
You could use startActivityForResult(Intent, int) in the parent Activity and override onActivityResult() in the child activity. See this tutorial for more details on how to implent this pattern.
I want to make a button appear in the MenuActivity layout but the deciding if statement is in the CapitalReceiver class. I've tried adding 'static' to various variables but it didn't work. Please help!
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class MenuActivity extends Activity {
String status;
Boolean verified = false;
String textColour = "#000000";
TextView mTvCapital;
ArrayAdapter<String> mAdapter;
Intent mServiceIntent;
CapitalReceiver mReceiver;
IntentFilter mFilter;
String country = "7ec47294ff3d8b74";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_layout);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Button IDButton = (Button) findViewById(R.id.getIt);
Button RefreshButton = (Button) findViewById(R.id.refresh);
long updateTimeMillis = System.currentTimeMillis();
String updateTime = (String) DateFormat.format("hh:mm", updateTimeMillis);
//If application has been submitted//
if(preferences.contains("first_middle_store") & !(verified)) {
status = "Status: Application pending. Last updated: " + updateTime;
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.VISIBLE);
textColour = "#000000";
}
//If application has not been submitted
else {
status = "Status: Application not yet submitted";
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.GONE);
textColour = "#000000";
}
TextView text=(TextView)findViewById(R.id.application_status);
text.setTextColor(Color.parseColor(textColour));
text.setText(status);
Button btnNextScreen = (Button) findViewById(R.id.verify);
//Listening to verify event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(), VerifyActivity.class);
startActivity(nextScreen);
}
});
Button btnNextScreen2 = (Button) findViewById(R.id.how);
//Listening to HowItWorks event
btnNextScreen2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen2 = new Intent(getApplicationContext(), HowItWorksActivity.class);
startActivity(nextScreen2);
}
});
//Listening to IDbutton event
IDButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen3 = new Intent(getApplicationContext(), IDActivity.class);
startActivity(nextScreen3);
}
});
}
#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, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_layout, container, false);
return rootView;
}
}
public void refresh(View view) {
// Getting reference to TextView
mTvCapital = (TextView) findViewById(R.id.tv_capital);
mTvCapital.setText("hello");
// Creating an intent service
mServiceIntent = new Intent(getApplicationContext(), CapitalService.class);
mServiceIntent.putExtra(Constants.EXTRA_ANDROID_ID, country);
// Starting the CapitalService to fetch the capital of the country
startService(mServiceIntent);
// Instantiating BroadcastReceiver
mReceiver = new CapitalReceiver();
// Creating an IntentFilter with action
mFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Registering BroadcastReceiver with this activity for the intent filter
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, mFilter);
}
// Defining a BroadcastReceiver
private static class CapitalReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String capital = intent.getStringExtra(Constants.EXTRA_APPROVAL);
if(capital == "YES") {
//status = "Status: Application Approved";//
//IDButton.setVisibility(View.VISIBLE);//
}
else if(capital == "NO"){
//status = "Status: Application Denied";//
}
}
}
}
Just glancing over your code, a possible solution (and perhaps not the best) would be to make the ID Button variable global. You would then instantiate it in the onCreate whilst still allowing it to be manipulated in other classes in this MenuActivity.
I hope this helps.
Hi Guys I am new with android programming and Java. I am trying to make a travel app. My issue is that how do I pass data from the selected item from the list to the editText filed. This is out I have done so far.. Pls. be kind I am newbee
The activity class that uses the ListActivity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class SelectStationActivity extends ListActivity {
String stations[] = { "Acton Main Line","Ealing","Great Western","Albany Park"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter <String> adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stations);
setListAdapter(adapter);
}
protected void OnListItemClick(ListView l, View v, int position, long id) {
String values = stations[(int) id];
Intent result = new Intent().putExtra("SELECTED_STATION_NAME", values);
setResult(RESULT_OK, result);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.select_station, menu);
return true;
}
The main class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TravelActivity extends Activity {
// The request code for the selectChkInBt
protected static final int SelectChkin_REQUEST_CODE = 1;
// The request code for the selectChkOutBt
protected static final int SelectChkout_REQUEST_CODE = 2;
private String checkinStation;
private String checkoutStation;
private Button checkinButton, checkoutButton, selectChkInButton, selectChkOutButton;
private EditText checkinEditText, checkoutEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_travel);
checkinButton = (Button) findViewById(R.id.btCkIn);
checkoutButton = (Button) findViewById(R.id.BtChkOut);
selectChkInButton = (Button) findViewById(R.id.btselectChkIn);
selectChkOutButton = (Button) findViewById(R.id.btselectChkOut);
checkinEditText = (EditText) findViewById(R.id.EditTxtChkIn);
checkoutEditText = (EditText) findViewById(R.id.EditTxtChkOut);
checkinButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkinEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-in Station", Toast.LENGTH_LONG).show();
} else {
checkinStation = checkinEditText.getText().toString();
// Enable the check-out EditText and Button
checkinEditText.setEnabled(false);
checkinEditText.setTextColor(Color.CYAN);
checkinButton.setEnabled(false);
// Disable the check-in- EdiText AND Button
checkoutEditText.setEnabled(true);
checkoutButton.setEnabled(true);
checkoutEditText.requestFocus();
}
}
});
checkoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkoutEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-Out station", Toast.LENGTH_LONG)
.show();
} else {
checkoutStation = checkoutEditText.getText().toString();
// Clear edit Text
checkoutEditText.setText("");
// Enable the check-in EditText and Button
checkoutEditText.setEnabled(false);
checkoutButton.setEnabled(false);
/*
* Disable the check-out EditText and Button, to allow the
* eternal cycle of checking in and out to commence once again */
checkinEditText.setText("");
checkinEditText.setEnabled(true);
checkinButton.setEnabled(true);
checkinEditText.requestFocus();
Toast.makeText(getApplicationContext(),
"Travel information added!", Toast.LENGTH_SHORT)
.show();
}
}
});
I could implement a inner class for the two select buttons but i have diffculties to do it.Pls. provide some help how I could implement it thanks.
selectChkInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,
SelectStationActivity.class);
startActivityForResult(intent, SelectChkin_REQUEST_CODE);
}
});
selectChkOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,SelectStationActivity.class);
startActivityForResult(intent, SelectChkout_REQUEST_CODE);
}
});
}
The onActivityResult is not responding here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== RESULT_OK){
if (requestCode == 1) {
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, "Recipt");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
public boolean OnMenuItemSelected(int featureId, MenuItem item) {
String Recipt = "Recipt" + item.getItemId() + "\nCheck-in: "
+ checkinStation + "\nCheck-Out: " + checkoutStation;
Toast.makeText(getApplicationContext(), Recipt, Toast.LENGTH_LONG)
.show();
return true;
}
protected void OnSaveInstanceState(Bundle outState) {
outState.putString("lAST_CHECKIN", checkinStation);
outState.putString("lAST_CHECKOUT", checkoutStation);
}
protected void onRestoreInstance(Bundle savedInstanceState) {
checkinStation = savedInstanceState.getString(checkinStation);
checkoutStation = savedInstanceState.getString(checkoutStation);
}
}
You Should use this
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
as
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME").toString());