Get Variable from another Activity (Android Studio) - java

I know that there are a lot of answers to this question already, but I'm still having trouble dealing with this concept.
An answer found here shows:
If you didn't want to use a global variable you could always create a method in your activity to return your string.
public String getMyString(){
return item; }
Then in your current activity you could call:
String myValue = LoginScreen.getMyString();
When I try this method, I am returned an error saying "Non-Static method can not be referenced from a static context". However if I make the method static it says that my variable needs to be static, but I need to update the variable. I'll include my code below.
First Activity -
btnSEARCH.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (editTextSearch.getText().toString() != null) {
SearchQueryTerm = editTextSearch.getText().toString();
editTextSearch.setText("");
}
}
});
public String getMyString(){
return SearchQueryTerm;
}
Second Activity-
String SearchQueryTerm = MainActivity.getMyString();
I truly appreciate any help you can give me in this. Thanks so much!! <3
This is my updated code - however it still crashes :(
Activity 1
public void sendMessageIntent(View view) {
Intent search_intent = new Intent(this, SearchActivity.class);
api_intent.putExtra("my_variable", SearchQueryTerm);
startActivity(search_intent);
}
xml file
<Button
android:id="#+id/button_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="View"
android:onClick="sendMessageIntent"
/>
Activity 2 -
public String SearchQueryTerm
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_variable);
if (extras != null) {
SearchQueryTerm = extras.getString("my_variable");
}
}

Use putExtra method of an object Intent.
In your first activity create for example :
String value = "value";
Intent i = new Intent(getApplicationContext(), MyActivity.class);
i.putExtra("my_variable",value);
startActivity(i);
In your second activity you can retrieve your variable :
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("my_variable");
}
It's the best method to pass a variable between activities.
To show you how it works, i have done this code :
XML of first activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editTextSearch"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonSearch"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Button"/>
</LinearLayout>
</RelativeLayout>
First Activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSEARCH = (Button) findViewById(R.id.buttonSearch);
btnSEARCH.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editTextSearch = (EditText) findViewById(R.id.editTextSearch);
if (editTextSearch.getText().toString() != null) {
String value = "value";
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("SearchQueryTerm",editTextSearch.getText().toString());
startActivity(i);
editTextSearch.setText("");
}
}
});
}
}
In this first activity we pass the value of the editText in the putExtra method with the key = "SearchQueryTerm".
To retrieve the value of editText do this in your second Activity :
public class Main2Activity extends AppCompatActivity {
String SearchQueryTerm = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
SearchQueryTerm = extras.getString("SearchQueryTerm");
}
System.out.println(SearchQueryTerm);
}
}
Now you have the value of your editText in the variable SearchQueryTerm ( Second Activity ).
It works for me, so there is no reason it dont work for you.
Hope it helps.

a good solution is to add a "model" singleton class, where you store data that have to be shared between your activities
example :
public class Model {
private static Model __instance == null;
private Model() {
}
public static Model instance() {
if (__instance == null) {
__instance = new Model();
}
return __instance;
}
private Object mydataToShare = null;
public void setMyDataToShare(Object mydataToShare) {
this.mydataToShare = mydataToShare;
}
public Object getMyDataToShare() {
return mydataToShare;
}
}
to store data :
Model.instance().setMyDataToShare(<value to store>);
to retrieve data :
Object valueToRetrieve = Model.instance().getMyDataToShare();
it allow you to transfer complex data and separate completely logic part from UI

Related

Why my app wont open after adding this line in my code : TextView t = findViewById(R.id.wina)"?

This is my codebase for a game but it won't open after adding line 4 if I don't use that line then my app works perfectly fine. and no error is thrown. it builds perfectly fine.
I'm new with android dev so I don't know much about it.
below is XML and java code for the TextView and APP respectively.
<TextView
android:id="#+id/wina"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/board"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="#string/hello"
android:visibility="invisible"
android:textSize="24sp"
/>
.
public class MainActivity extends AppCompatActivity {
int flag = 1; //1 means red and 0 means yellow
int[] gameState = {-1,-1,-1,-1,-1,-1,-1,-1,-1}; //-1 empty , 0 yellow and 1 red
**TextView tv = findViewById(R.id.wina);**
String win ="";
int[][] winningConditions = {
{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}
};
boolean gameActive = true;
public boolean check(){
for(int[] winningCondition : winningConditions){
if(gameState[winningCondition[0]]==gameState[winningCondition[1]] &&
gameState[winningCondition[1]]==gameState[winningCondition[2]] &&
gameState[winningCondition[0]]!=-1){
return true;
}
}
return false;
}
public void dropToken(View view){
ImageView vi = (ImageView) view;
int tag = Integer.parseInt(vi.getTag().toString());
if(gameState[tag]==-1) {
gameState[tag] = flag;
vi.setY(-1500);
if (flag == 1 && gameActive) {
vi.setImageResource(R.drawable.red);
flag = 0;
}
else if (flag == 0 && gameActive) {
vi.setImageResource(R.drawable.yellow);
flag = 1;
}
vi.animate().translationY(0).setDuration(400);
if(check()){
if(flag==1){
win = "yellow";
}
else{
win = "red";
}
Toast.makeText(this,win, Toast.LENGTH_SHORT).show();
gameActive=false;
}
}
#Override protected void onCreate(Bundle savedInstanceState) {
//normal code } }
You have not drawn your XML file of MainActivity yet and you are calling a method to find your textview before actually drawing your activity. So, first you need to implement onCreate() method of AppCompatActivity and set it's content view using setContentView() and only then you initialize your TextView field.
Refer the below sample and make changed accordingly to your code.
public class MainActivity extends AppCompatActivity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.wina);
}
}
Read more about Activity Lifecycle

flash cards showing blank card android

I am creating a flash card app in android.
For some reason when you hit the button for next card it will randomly show either the next card or a blank card. Sometimes it will be a whole heap of blank cards then one with information. Please find the code below. I am new to creating apps but have done java in the past, it works perfectly in netbeans but not when you run the app.
I want the cards to only appear once thats what the num arraylist is for, it holds the index numbers for the names arraylist. so it appears once but will show blank cards when it shouldnt be. eg: card with info, card without info, card with info. sometimes it will show multiple empty cards then one with info, that is my problem.
I know i havent commented the code,
The first activity:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Character.createArrays();
}
/**
* Called when the user taps the Start button
*/
public void sendMessage(View view) {
Character.getCharName();
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
}
}
The second activity where the cards are called:
public class DisplayMessageActivity extends AppCompatActivity {
public static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(DisplayMessageActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
;
}
public void refresh(View view) {
Character.getCharName();
overridePendingTransition(0, 0);
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
this.finish();
overridePendingTransition(0, 0);
}
The methods to get the cards, There are arraylists and the arrays are created correctly and the string arrays are inputted correctly. the CharacterNames array is just an array with names in them. the num array just has index numbers inputted and checked:
public void getCharName() {
RandomNumGen();
mMessage = "";
message = "";
while (num.contains(mRandom)) {
RandomNumGen();
}
for (int i = 0; i < CharacterNames.size(); i++) {
if (i == mRandom) {
mMessage = CharacterNames.get(i);
if (i == mRandom && CharacterNames.contains(mMessage)) {
num.add(mRandom);
card();
}
}
}
}
public void RandomNumGen() {
mRandom = (int) (Math.random() * CharacterNames.size());
}
public String card() {
String[] array;
for (int y = 0; y < names.size(); y++) {
if (Arrays.asList(names.get(y)).contains(mMessage)) {
array = (names.get(y));
for (String array1 : array) {
if (array1 != null && array1.length() > 0) {
message += "\n" + "\n" + (array1);
}
}
Arrays.fill(array, null);
}
}
return message;
}
I hope thats enough information to help.
Thank you so much for understanding an helping me
activity display message xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayMessageActivity">
<TextView
android:id="#+id/textView"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="#string/textview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:onClick="refresh"
android:text="#string/next_char"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:text="Next character" />
</android.support.constraint.ConstraintLayout>
enter code here

App has stopped - ProgressBar in Android

friends. I started to learn Android app developinng with Android Studio and Java. Now i am trying to make one progressbar. When app is started we have two EditText fields where first is 100 by default(how will be the max value for progressbar ) and one EditText field for increment by(this is step) for progressbar. When we click Start it must show up via dialog.
I write the code, there is no more errors, but app is closing when i hit the Start Button. The progressbar is not working
This is the code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/txt_max"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Max Value" />
<EditText
android:id="#+id/maximum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100.0" />
<TextView
android:id="#+id/txt_increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Increment by"/>
<EditText
android:id="#+id/increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5.0" />
<Button
android:id="#+id/butt_Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
</LinearLayout>
This is the MainActivity.java:
public class MainActivity extends AppCompatActivity {
int increment;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button) findViewById(R.id.butt_Start);
startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
EditText et = (EditText) findViewById(increment);
increment = Integer.parseInt(et.getText().toString());
dialog = new ProgressDialog(MainActivity.this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
EditText max = (EditText) findViewById(R.id.maximum);
int maximum = Integer.parseInt(max.getText().toString());
dialog.setMax(maximum);
dialog.show();
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
while (dialog.getProgress() <= dialog.getMax())
{
Thread.sleep(500);
progressHandler.sendMessage(progressHandler.obtainMessage());
}
} catch (java.lang.InterruptedException e)
{
}
}
});
background.start();
}
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
}
};
});
}
}
There are some error with that code.. I will comment each by reporting your snippet:
public class MainActivity extends AppCompatActivity {
int increment;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button) findViewById(R.id.butt_Start);
startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
EditText et = (EditText) findViewById(increment);
Here is the first error: not really a wrong thing, but it's better to istantiate the EditText in your onCreate (outside the onClick), because this way you will re-create the EditText every time you click the button.
The error is double: you are using findViewById(increment) where, in your code, increment is an int variable whose value is actually 0. You have to use (as you did for the button)
findViewById(R.id.increment);
Going on:
increment = Integer.parseInt(et.getText().toString());
dialog = new ProgressDialog(MainActivity.this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
EditText max = (EditText) findViewById(R.id.maximum);
int maximum = Integer.parseInt(max.getText().toString());
Here the error is xml side: since you are assuming that max.getText().toString() is an Integer, add inputType to your xml with number value.
dialog.setMax(maximum);
dialog.show();
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
while (dialog.getProgress() <= dialog.getMax())
{
Thread.sleep(500);
progressHandler.sendMessage(progressHandler.obtainMessage());
}
} catch (java.lang.InterruptedException e)
{
}
}
});
background.start();
}
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
}
};
});
}
}
Another thing is that is better to avoid naming a variable with same name of your id, expecially because id should be representative of the control you are pointing at (for example call it "EditTextMaxValueMainActivity", this is a limit example but it is representative).
If I can suggest you, TheNewBoston channel/site is the best for tutorials, it has a couple of playlist with android basics to advanced and it is simple and really explicative. Good luck!
for other errors, we will need the logtrace
The Answer for me is here:
This line:
EditText et = (EditText) findViewById(increment);
Must be changed to:
EditText et = (EditText) findViewById**(R.id.increment)**;
And i go to design view of activity_main.xml and changed the inputType of increment EditText and maximum EditText to number.
And removed the decimal format from the numbers.
<EditText
android:id="#+id/increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5" />
And here i had number with decimal, now i removed them.
<EditText
android:id="#+id/maximum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100" />

Android Studio retrieve information from XML in a override method

Sorry for the noob question but I did not come across any situations that would work for me. Im sure this is super simple, I just need to be pointed in the right direction.
Objective:
I want to be able to take the name of what the user specified and add it to the markers title.
What I know:
I am unable to inflate the xml and grab it via that way cause the method is being override and if I inflate to my knowledge will no longer allow me to override the method. How should I approach this?
MapsAcitivy
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, addPlace.Communicator {
private GoogleMap mMap;
public static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 0;
int mStackLevel;
int YES_NO_CALL;
FragmentManager manager = getSupportFragmentManager();
final Context context = this;
#InjectView(R.id.btn_login) Button _loginButton;
ClusterManager<ClusterRequest> mClusterManager;
class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
// These are both viewgroups containing an ImageView with id "badge" and two TextViews with id
// "title" and "snippet".
private final View mWindow;
//private final View mContents;
CustomInfoWindowAdapter() {
mWindow = getLayoutInflater().inflate(R.layout.info_window_layout, null);
//mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
}
#Override
public View getInfoWindow(Marker marker) {
render(marker, mWindow);
return mWindow;
}
#Override
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
LatLng latLng = marker.getPosition();
// Getting reference to the TextView to set latitude
TextView tvLat = (TextView) v.findViewById(R.id.tv_lat);
// Getting reference to the TextView to set longitude
TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);
// Setting the latitude
tvLat.setText("Latitude:" + latLng.latitude);
// Setting the longitude
tvLng.setText("Longitude:"+ latLng.longitude);
// Returning the view containing InfoWindow contents
return v;
//render(marker, mContents);
//return mContents;
}
private void render(Marker marker, View view) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
#TargetApi(23)
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
// MY_PERMISSION_ACCESS_FINE_LOCATION is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
LocationManager initialLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String initialProvider = initialLocationManager.getBestProvider(criteria, true);
Location initialLocation = initialLocationManager.getLastKnownLocation(initialProvider);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
double initialLatitude = initialLocation.getLatitude();
double initialLongitude = initialLocation.getLongitude();
LatLng initialLatLng = new LatLng(initialLatitude, initialLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(initialLatLng, 14.9f));
//mMap.setOnInfoWindowClickListener(this);
mClusterManager = new ClusterManager<ClusterRequest>(getApplicationContext(), mMap);
mMap.setOnCameraChangeListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
}
}
public void onButtonClick(View view){
//do something when button is clicked.
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.add_place);
dialog.setTitle("Add Place");
Button btnLogin = (Button) dialog.findViewById(R.id.addPlacebtnSubmit);
Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
final EditText txtUsername = (EditText)dialog.findViewById(R.id.txtStopName);
// Attached listener for add place GUI button
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stopName = txtUsername.getText().toString();
if(stopName.length() > 4){
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(MapsActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
// MY_PERMISSION_ACCESS_FINE_LOCATION is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
LocationManager currentLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria currentCriteria = new Criteria();
String currentProvider = currentLocationManager.getBestProvider(currentCriteria, true);
Location currentLocation = currentLocationManager.getLastKnownLocation(currentProvider);
double currentLatitude = currentLocation.getLatitude();
double currentLongitude = currentLocation.getLongitude();
LatLng currentLatLng = new LatLng(currentLatitude, currentLongitude);
ClusterRequest testCluster = new ClusterRequest(currentLatitude, currentLongitude);
mClusterManager.addItem(testCluster);
mClusterManager.setRenderer(new MapIconRender(getApplicationContext(), mMap, mClusterManager));
dialog.dismiss();
}
else{
txtUsername.setError("Stop name must be at least 5 characters long.");
}
}
});
}
MapIconRender.java
public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> {
public MapIconRender(Context context, GoogleMap map,
ClusterManager<ClusterRequest> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions
markerOptions){
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure));
markerOptions.snippet("Status: ");
markerOptions.title(stopName); //<------ THIS IS WHERE I WANT THE STOP NAME TO BE WHAT THE USER ENTERED.
super.onBeforeClusterItemRendered(item, markerOptions);
}
}
add_place.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_height="match_parent"
android:paddingLeft="10dp" android:paddingRight="10dp"
android:background="#fff" android:layout_width="300dp"
android:paddingTop="10dp">
<View
android:id="#+id/HorizontalLine"
android:layout_width="match_parent"
android:layout_height="1dip"
android:background="#aaa" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Name:"
android:paddingTop="20dp"
android:id="#+id/name" />
<EditText android:layout_height="wrap_content"
android:id="#+id/txtStopName"
android:maxLength="100"
android:singleLine="true"
android:hint="Name of this stop (5-100 characters)"
android:layout_width="match_parent">
<requestFocus></requestFocus>
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Type:"
android:paddingTop="20dp"
android:layout_marginBottom="10dp"
android:id="#+id/type" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:entries="#array/type_arrays"
android:prompt="#string/type_prompt"
android:layout_marginBottom="10dp"/>
<View
android:id="#+id/HorizontalLine2"
android:layout_width="match_parent"
android:layout_height="1dip"
android:background="#aaa" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/linearLayout1"
android:paddingTop="5dp">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="0.5"
android:id="#+id/btnCancel" android:text="Cancel"
android:onClick="addPlaceCancel"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="0.5"
android:id="#+id/addPlacebtnSubmit" android:text="Submit"
android:onClick="addPlaceSubmit"
android:layout_marginBottom="10dp"/>
</LinearLayout>
</LinearLayout>
ClusterRequest.java
public class ClusterRequest implements ClusterItem {
private final LatLng mPosition;
public ClusterRequest(double lat, double lng) {
mPosition = new LatLng(lat, lng);
}
#Override
public LatLng getPosition() {
return mPosition;
}
}
Can't you override onClusterItemRendered() method?
I think you can save your marker name in onBeforeClusterItemRendered() to any class-global variable String, and set the marker name in onClusterItemRendered() with Marker.setTitle(yourSavedTitle); or something.
Something like this:
public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> {
private String mMarkerTitle;
public MapIconRender(Context context, GoogleMap map,
ClusterManager<ClusterRequest> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions
markerOptions){
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure));
markerOptions.snippet("Status: ");
markerOptions.title(stopName); //<------ THIS IS WHERE I WANT THE STOP NAME TO BE WHAT THE USER ENTERED.
mMarkerTitle = stopName;
super.onBeforeClusterItemRendered(item, markerOptions);
}
#Override
protected void onClusterItemRendered (ClusterRequest item, Marker marker){
marker.setTitle(mMarkerTitle);
}
}
#SuhyeonLee Not sure if this is what you meant (please let me know) but I did find the answer surprisingly enough in the demo that google released for their customize cluster demo. Heres what I learned. When calling the MapIconRender.java class via
mClusterManager.setRenderer(new MapIconRender(getApplicationContext(), mMap, mClusterManager));
Which will run this method in the MapIconRender.java class
protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions
markerOptions)
Which means whatever variables in the ClusterRequest class will be accessible here in the MapIconRender.java class and can be accessed via (item.variableName). I apologize for not posting the code for the file ClusterRequest, I didnt think it was needed. ill go back and add that snippet to my original question.
Anyway the new code I needed to add was as follows:
In the MapsActivity class I needed to pass the ClusterRequest class the name of the marker(or title of the marker) via:
ClusterRequest testCluster = new ClusterRequest(currentLatitude, currentLongitude, stopName); //stopName was added here.
And in the ClusterRequest class I needed to add the "global variable" of the marker name (aka stopName) via:
public class ClusterRequest implements ClusterItem {
private final LatLng mPosition;
public final String stopName; //Add a "global variable" here so it can be accessible in the MapIconRender class.
public ClusterRequest(double lat, double lng, String _stopName) {
mPosition = new LatLng(lat, lng);
stopName = _stopName;
}
#Override
public LatLng getPosition() {
return mPosition;
}
}
And finally in my MapIconRender.java class I can add the title name of the marker via:
public class MapIconRender extends DefaultClusterRenderer<ClusterRequest> {
public MapIconRender(Context context, GoogleMap map,
ClusterManager<ClusterRequest> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered (ClusterRequest item, MarkerOptions
markerOptions){
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_outside_azure));
markerOptions.snippet("Status: ");
markerOptions.title("Title: " + item.stopName); //Now we can access the title of the marker by calling item.variableName
super.onBeforeClusterItemRendered(item, markerOptions);
}
}
Im really sorry about the noob question here but I hope this helps someone out that may have the same question as I did and thank you for your answers! "SO" community is awesome!

Camera Intent ACTION_IMAGE_CAPTURE and put extra data

I want to put extra data to an Intent Camera, that seems simple...
It WAS working some days ago, but I made a lot of changes on code, avd and target version and now it is not working.
The project is now on target version 11.
In fact my goal is to pass an id from my database to construct image name but here a simple code to illustrate my issue.
Here's the sample code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".CameraTestActivity" >
<Button
android:id="#+id/buttonpic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="76dp"
android:text="Button" />
</RelativeLayout>
-
public class CameraTestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_test);
Button buttonpic = (Button)findViewById(R.id.buttonpic);
buttonpic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
///first try to put extra data
cameraIntent.putExtra("thisone", "ArgumentFrom");
///second try to put extra data
Bundle extras = new Bundle();
extras.putBoolean("thisalso",true);
cameraIntent.putExtras(extras);
///start camera activty with ID
startActivityForResult(cameraIntent, 1888);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
///if pic is picked and Intent ID is Camera one i.e. 1888
if (requestCode == 1888 && resultCode == RESULT_OK) {
///first try >> Not working
Bundle extra = getIntent().getExtras();////
if (extra != null) {
Log.d("extra: ","isnotnull");
Boolean inputThatIwant = extra.containsKey("thisone");
Boolean inputThatIwantBool = extra.containsKey("thisalso");
Log.d("thisone",inputThatIwant.toString());
Log.d("thisalso",inputThatIwantBool.toString());
}
///Second try >> Some Data is back (pic data... ?)
Bundle extras = data.getExtras();
if (extras != null) {
Log.d("extras: ","isnotnull"); /////-->>Print "isnotnull"
Boolean inputThatIwant = extras.containsKey("thisone");
Boolean inputThatIwantBool = extras.containsKey("thisalso");
Log.d("thisone",inputThatIwant.toString()); /////-->>Print "false"
Log.d("thisalso",inputThatIwantBool.toString()); /////-->>Print "false"
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.camera_test, menu);
return true;
}
}
[EDIT]
Here how I deal with this finally, it can help someone perhaps...
I just "share" within the same class my ID:
private String inputid;
When it's called by Camera request I fill the id in the inputid String and obviously on OnresultActivity this String could not be null, so it works as simple as that...
But if someone has a better solution I'll take it!
Regards....
I don't if its a good prog idea but i created the Uri which i was passing in the intent as a private static member for this class and created a public static function to return this Uri and since in my case I was getting back the result in one of the fragment class of this class , in its(fragment's class) onActivityResult instead of using the the Intent Data parameter which was null(as i found) i used that Uri directly by calling the function(that i created to return Uri). And.... it worked :)

Categories

Resources