I'm having some trouble with an issue in my Android Studio application that is to do with pressing the back button. Basically the user inputs into a text view and another method (not included as it works fine but I can post if requested) searches an API for the relevant data and displays it in a recycler view. Then the user makes a selection from the recycler view and the method below parses a JSON file and adds relevant data from it to an array in a separate class "Director". Once this happens the next activity "GraphActivity" starts and draws a number of nodes on a canvas for each director in the array.
The issue I am having is that when I make an input into the text view and then press the back button to close the soft keyboard on my Android device (it covers up the recycler view) and go through the steps I just mentioned, when the GraphActivity activity starts it does not work (no nodes are drawn). However, if I then press the back button to go back to the first activity and then make the same selection from the recycler view again, it works.
From what I can tell, the issue seems to be with the data being added to the "Director" array but I cannot figure out what is causing it, Logcat shows that the first time the GraphActivity activity starts the "Director" array is empty and therefore, no nodes are drawn but when I press back and then make the same selection again the array has the correct data and the nodes are drawn.
I would really appreciate some help with this as I am very new to Android Studio and have been searching around for hours to try and find a solution.
public class MainActivity extends AppCompatActivity implements MainAdapter.OnCompanyClickedListener {
private RecyclerView recyclerView;
private TextView userInput;
private Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rView);
RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
}
//Parse JSON File
public void searchCompanyDirectors(final String companyNumber){
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
HttpClient httpClient = new HttpClient();
try{
final String response = httpClient.run("myURL");
runOnUiThread(new Runnable(){
#Override
public void run(){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("items");
for (int i = 0; i < array.length();i++){
JSONObject o = array.getJSONObject(i);
String appointment = o.getString("links");
String parsedAppointment = parseApp(appointment);
Director director = new Director(o.getString("name"),parsedAppointment);
Director.directorList.add(director);
}
}catch (JSONException e){
e.printStackTrace();
}
}
});
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
thread.start();
}
#Override
public void onCompanyClicked(int position) {
Toast.makeText(this,Company.companyList.get(position).getTitle(),Toast.LENGTH_LONG).show();
chosenCompanyNumber = Company.companyList.get(position).getCompanyNumber();
chosenCompany = Company.companyList.get(position).getTitle();
searchCompanyDirectors(chosenCompanyNumber);
Intent intent = new Intent(this,GraphActivity.class);
startActivity(intent);
}
}
The GraphActivity class:
public class GraphActivity extends AppCompatActivity {
DrawGraph drawGraph;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawGraph = new DrawGraph(this);
setContentView(drawGraph);
The DrawGraph class:
public class DrawGraph extends View {
private Paint p1;
private Paint p2;
private Paint p3;
private Paint paint;
private Path path;
private Point point1;
private int radius = 300;
double x;
double y;
double angle;
int mWidth = this.getResources().getDisplayMetrics().widthPixels;
int mHeight = this.getResources().getDisplayMetrics().heightPixels;
List<Director> directorList = Director.getDirectorList();
private String chosenCompany = MainActivity.getChosenCompany();
private static List<Float> ordinates = new ArrayList<>();
public DrawGraph(Context context) {
super(context);
p1 = new Paint(Paint.ANTI_ALIAS_FLAG);
p1.setStrokeWidth(10);
p2 = new Paint(Paint.ANTI_ALIAS_FLAG);
p2.setStrokeWidth(10);
p3 = new Paint(Paint.ANTI_ALIAS_FLAG);
p3.setStrokeWidth(5);
path = new Path();
paint = new Paint();
point1 = new Point(mWidth/2, mHeight/2);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Colors
p1.setStyle(Paint.Style.FILL);
p1.setColor(Color.RED);
p2.setStyle(Paint.Style.FILL);
p2.setColor(Color.GREEN);
p3.setStyle(Paint.Style.STROKE);
p3.setColor(Color.CYAN);
paint.setColor(Color.BLACK);
paint.setTextSize(18f);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.CENTER);
Rect bounds = new Rect();
paint.getTextBounds(chosenCompany, 0, chosenCompany.length(),bounds);
//Draw company and directors
for (int i = 1; i <= directorList.size(); i++)
{
//Divide the company node
angle = i * (360/directorList.size());
x = point1.x + radius * cos(angle);
y = point1.y + radius * sin(angle);
//Draw directors
canvas.drawCircle((float)x,(float)y - (bounds.height() / 2), bounds.width() + 5,p2);
canvas.drawText(directorList.get(i-1).getName(),(float)x,(float)y,paint);
}
Okay, I've found an issue in DrawGraph class noted here;
List<Director> directorList = Director.getDirectorList();
private String chosenCompany = MainActivity.getChosenCompany();
You should not directly access the data objects of one activity from another. The previous activity could be destroyed etc as per Android OS and its lifecycle. You must think of it like out of sight, out of memory; which can cause the current activity to not be able to access the data in the previous one.
You'd need to properly send the parsed data from your JSON file, the variables List directorList and the String chosenCompany from your MainActivity to GraphActivity.
You can send data from one activity to another by adding it to the intent with which you call the next activity. The Intent class has features to help you send a small amount of information via itself; called putExtra() and getExtra(). More about them here.
You will need to add those variable datasets through intent.putExtra and fetch them back in your other activity onCreate by using getExtras.
Activity A >> Intent call to Activity B + Data >> Activity B
Hope this helps.
Related
Assumption and what I want to achieve
I'm working on an application that receives current location information from an external RTK-GPS via serial communication, and draws dots or lines on an osmdroid map.
I have already realized receiving the location information and converting the received data to a type that can be displayed on TextView.
For serial communication, I am using FTDI's "usb-serial-for-android" library, and for map functions, I am using "osmdroid".
Currently
Receive location data from RTK-GPS via serial communication.
Get the latitude and longitude in double type from the received data (String type).
Create a GeoPoint from the acquired latitude and longitude, set it to a marker, and draw it on the map. At this time, the GeoPoint is also stored in the GeoPoint list.
The following procedure is used to display the marker of the current location on the map. Currently, the received latitude and longitude are set to the marker and all the markers are drawn.
Eventually, I'd like to draw the trajectory of movement as a line while updating the current location marker.
Problems and error messages
The problem we are experiencing is that when we start drawing, the application immediately becomes sluggish and freezes.
Since 10 data are sent from GPS per second, if we try to draw all the received data on the map, the number of markers will be huge and the app will freeze.
Therefore, we tried to draw markers in 10 marker skips, but even so, the application became sluggish and froze as soon as it started drawing.
Next, when the number of data exceeded 100, I deleted the oldest data first, and the application did not freeze after starting drawing. However, I don't think it is possible to draw all the loci with this method. If possible, I would like to draw all the loci that have been moved.
My questions are as follows.
Is it possible to draw the movement locus using the above method and policy?
Is it impossible to draw such a moving locus in Android?
Does OSMDROID have a function to draw the movement locus?
Are there any similar questions?
Please let me know.
Here is my code.
public class MapGeneratorMainActivity extends Activity {
private static final double MAP_ZOOM = 15.0;
private static final double MAP_ZOOM2 = 17.0;
static MapView mapGeneratorMainMap = null;
public static List<Marker> currentMarkers = new ArrayList<>();
ArrayList<GeoPoint> currentPoints = new ArrayList<>();
ArrayList<GeoPoint> currentPoints2hz = new ArrayList<>();
ArrayList<Polyline> currentTrajectory = new ArrayList<>();
public static int receiveCount = 0;
public static GeoPoint currentP2hz;
public MapGeneratorMainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
org.osmdroid.config.Configuration.getInstance().load(getApplicationContext(),
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()));
setContentView(R.layout.map_generator_main_activity);
MapView mapGeneratorMainMap = findViewById(R.id.MapGaneratorMainMap);
mapGeneratorMainMap.setMultiTouchControls(true);
IMapController mapController = mapGeneratorMainMap.getController();
mapController.setZoom(MAP_ZOOM);
GeoPoint centerPoint = new GeoPoint(aveLat, aveLon);
mapController.setCenter(centerPoint);
mapGeneratorMainMap.setTilesScaledToDpi(true);
final MapTileProviderBasic tileProvider = new MapTileProviderBasic(getApplicationContext());
ITileSource tileSource = new XYTileSource("GSI", 14, 24, 256, ".jpg", new String[]{TILE_SEVER});
tileProvider.setTileSource(tileSource);
final TilesOverlay tilesOverlay = new TilesOverlay(tileProvider, this.getApplicationContext());
tilesOverlay.setLoadingBackgroundColor(Color.TRANSPARENT);
mapGeneratorMainMap.getOverlays().add(tilesOverlay);
mapGeneratorMainMap.invalidate();
FloatingActionButton myLocationButton = findViewById(R.id.myLocationButton);
myLocationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentService = new Intent(getApplication(), gpsService.class); //位置情報受信サービス
intentService.putExtra("REQUEST_CODE", 1);
startForegroundService(intentService);
}
});
//Receiver
UpdateReceiver receiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("DO_ACTION");
registerReceiver(receiver, filter);
}
protected class UpdateReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String currentLat = null;
String currentLon = null;
MapView mapGeneratorMainMap = findViewById(R.id.MapGaneratorMainMap);
mapGeneratorMainMap.setMultiTouchControls(true);
IMapController mapController = mapGeneratorMainMap.getController();
mapController.setZoom(MAP_ZOOM2);
Bundle extras = intent.getExtras();
String msg = extras.getString("message"); //String型の位置情報
TextView currentLocatonTextView = findViewById(R.id.CurrentLocation);
currentLocatonTextView.setText(msg);
String[] currentLocaton = msg.split(",", -1);
currentLat = currentLocaton[0];
currentLon = currentLocaton[1];
double Lat = Double.parseDouble(currentLat);
double Lon = Double.parseDouble(currentLon);
GeoPoint currentP = new GeoPoint(Lat, Lon);
if(receiveCount == 0){
currentP2hz = new GeoPoint(Lat, Lon);
currentPoints.add(currentP);
currentPoints2hz.add(currentP2hz);
currentPtMarker = new Marker(mapGeneratorMainMap);
Drawable currentMarkerIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.current_point_marker, null);
currentPtMarker.setIcon(currentMarkerIcon);
currentPtMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER);
currentPtMarker.setPosition(currentP);
currentMarkers.add(currentPtMarker);
mapGeneratorMainMap.getOverlayManager().add(currentPtMarker);
mapGeneratorMainMap.invalidate();
}
else if(receiveCount == 100) {
currentPoints.add(currentP);
currentP2hz = new GeoPoint(Lat, Lon);
currentPoints2hz.add(currentP2hz);
receiveCount = 0;
currentPtMarker = new Marker(mapGeneratorMainMap);
Drawable currentMarkerIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.current_point_marker, null);
currentPtMarker.setIcon(currentMarkerIcon);
currentPtMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER);
currentPtMarker.setPosition(currentP);
currentMarkers.add(currentPtMarker);
mapGeneratorMainMap.getOverlayManager().add(currentPtMarker);
mapGeneratorMainMap.invalidate();
}
if(currentMarkers.size() >= 100){
currentMarkers.get(0).remove(mapGeneratorMainMap);
currentMarkers.remove(0);
}
receiveCount += 1;
}
}
Good morning everyone.
I was able to solve this problem.
The reason why it didn't work was that some of the data received by serial communication was not good.
After eliminating this bad data and receiving only the good data, I was able to do what I wanted.
thanks so much.
I am still a beginner and this is my first post here on the forum, sorry if the format of the question is not the right one.
I have an array of Resources in a class called DatabaseTagWalk that I use to find the id of a button in the MainActivity class.
This is the class where I store the id (in the activity_main.xml file i have created 6 buttons and assigned to them the same names as down here
public class DatabaseTagWalk {
int[] iconWalkId;
public DatabaseTagWalk(){
iconWalkId = new int[6];
iconWalkId[0] = R.id.topsightswalk;
iconWalkId[1] = R.id.literarypariswalk;
iconWalkId[2] = R.id.secretpassageswalk;
iconWalkId[3] = R.id.picnictimewalk;
iconWalkId[4] = R.id.joggitwalk;
iconWalkId[5] = R.id.deluxegardenswalk;
}
}
And this is the main activity class where I look for the id of the button to set a specific text and to specify the parameters used when the button is clicked
public class MainActivity extends AppCompatActivity {
DatabaseWalks listofwalks;
DatabaseTagWalk tagWalk;
Button[] buttons;
int buttonClicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listofwalks = new DatabaseWalks();
tagWalk = new DatabaseTagWalk();
for (int i = 0; i < listofwalks.walkList.length; i++) {
buttons[i] = (Button) findViewById(tagWalk.iconWalkId[i]);
buttons[i].setText(listofwalks.walkList[i].returnWalk());
setOnClick(buttons[i], tagWalk.iconWalkId[i]);
}
}
public void setOnClick(Button button, final int buttonTag ){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked = buttonTag;
Intent startingGame = new Intent("android.intent.action.SECONDACTIVITY");
startingGame.putExtra("buttonTag", buttonClicked);
startActivity(startingGame);
}
});
}
}
When i run the app I get the error:
"Attempt to write to null array" in the MainActivity at the line:
buttons[i] = (Button) findViewById(tagWalk.iconWalkId[i]);
You did not initialize your buttons list. You told that this variable exist, but you did not assign any value.
Change your line:
Button[] buttons;
to (if you know size - e.g. 10):
Button[] buttons = new Button[10];
or if wyou would like base on walkList size:
// After this line
listofwalks = new DatabaseWalks();
// Add new line, because here you know the list size
buttons = new Button[listofwalks.walkList.length];
I've got 2 activities and a class that extends Application where I'm trying to store global variables with a kind of setter getter functions.
The main activity sets some views and a chart; then calls the second activity which should be setting values to be used afterwards on the previous chart.
Then pressing backbutton and returning to the previous activity onRestart is called and the chart is refreshed.
The problem is I lose my theorically global variables somewhere. Debugging i realized that the functions work perfectly fine while im adding values in the second activity but when I return to the first activity globalXCount returns '0' again. Why is that?
I think im missunderstanding some point regarding lifecycles.
I attach some fragments of the code.
First activity:
public class MainActivity extends Activity {
Global glObj = new Global();
CombinedChart mChart;
private int itemcount;
float displayed;
private final List<String> mMonthList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
mChart = (CombinedChart) findViewById(R.id.mchart);
populateHeaderList();
setChartSettings();
Intent intent = new Intent(MainActivity.this, QandA.class);
startActivity(intent);
}
#Override
protected void onRestart() {
super.onRestart();
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
populateHeaderList();
setChartSettings();
}
Second activity:
public class QandA extends Activity {
Global glObj = new Global();
ViewFlipper flipper;
private float lastX;
...
}else{
//TODO If all information if correctly filled
trainedmins = et1.getText().toString();
localLineValue = Integer.parseInt(trainedmins) * Integer.parseInt(statusQ1);
//Add values to lines
glObj.setLineXvalues(localLineValue);
// TODO Add new Bar value //
//Add 1 more value to count
glObj.addGlobalXCount();
}
...
Global class:
public class Global extends Application {
//TODO
public Integer globalXCount;
private List<Integer> lineXvalues = new ArrayList<>();
private List<Integer> barXvalues = new ArrayList<>();
//////
public Integer getGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
return this.globalXCount;
}else{
return this.globalXCount;
}
}
public void addGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
}else{
this.globalXCount = this.globalXCount + 1;
}
}
Thanks in advance.
First of all, register your custom Application context in AndroidManifest.xml within the <application>-tag.
<application
android:name="<your_package>.Global" ...>
Access the global application context within your activities like this:
Global glObj = (Global) getApplicationContext();
glObj.addGlobalXCount();
Do not create a new instance with new! Always retrieve the instance via getApplicationContext().
Furthermore, I would suggest you to initialize your class field glObj within the onCreate()-method of your Activities.
I'm an Android newbie developer and having an issue with a tiny Android app I'm developing which I suspect is related to timing of dynamic view creation. It's a little scorekeeper app and it has dynamically generated player buttons and text fields, defined in a Player class. Here's an excerpt of how I'm doing this:
public Player(String name, int score, int number, boolean enabled, RelativeLayout mainScreen, List<Button> presetButtonList, Editor editor, Context context) {
super();
this.name = name;
this.score = score;
this.number = number;
this.enabled = enabled;
this.editor = editor;
// Get the lowest child on the mainScreen
Integer count = mainScreen.getChildCount(), lowestChildId = null;
Float lowestChildBottom = null;
for (int i = 0; i < count; i++) {
View child = mainScreen.getChildAt(i);
if ((lowestChildId == null || child.getY() > lowestChildBottom) &&
!presetButtonList.contains(child)) {
lowestChildId = child.getId();
lowestChildBottom = child.getY();
}
}
playerNameText = (EditText) setTextViewDefaults(new EditText(context), name);
playerNameText.setSingleLine();
// playerNameText.setMaxWidth(mainScreen.getWidth());
// playerNameText.setEllipsize(TextUtils.TruncateAt.END); //TODO: Prevent names which are too long for screen
playerNameText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable changedText) {
setName(changedText.toString());
updateScreen();
}
public void beforeTextChanged(CharSequence changedText, int start, int count, int after) {}
public void onTextChanged(CharSequence changedText, int start, int before, int count) {}
});
RLParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (lowestChildId != null) {
RLParams.addRule(RelativeLayout.BELOW, lowestChildId);
} else {
RLParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
RLParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
}
RLParams.setMargins(0, 10, 0, 10);
mainScreen.addView(playerNameText, RLParams);
the class further defines buttons and etc in a similar fashion, aligning tops with the name text view. I call this when a user clicks a button to add a player, and it works fine, displaying each player below the first on down the screen. The problem comes in when I'm loading a bunch of saved players at the start. Here's where i load the players:
public void loadData() {
RelativeLayout mainScreen = (RelativeLayout)findViewById(R.id.relativeLayout);
playerCount = savedData.getInt("playerCount", playerCount);
Player player;
String name;
playerList.clear();
for (int i=1; i<=playerCount; i++) {
name = savedData.getString("name" + i, null);
if (name != null) {
Log.v("name", name);
player = new Player(name, savedData.getInt("score" + i, 0), i, savedData.getBoolean("enabled" + i, false), mainScreen, presetButtonList, editor, this);
playerList.add(player);
player.updateScreen();
}
}
updateScreen();
}
Finally, I call the loadData() method when the app starts, here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedData = this.getPreferences(Context.MODE_PRIVATE);
editor = savedData.edit();
presetButtonList.add((Button)findViewById(R.id.newGame));
presetButtonList.add((Button)findViewById(R.id.addPlayer));
presetButtonList.add((Button)findViewById(R.id.removePlayer));
loadData();
}
The result? When there are more than two players to load, all the players get loaded to the same spot, on top of Player 2.
I suspect somehow that the players are all being generated at the same time and thus all believing that the lowest player view is Player 1, and not checking each other. I've tried triggering the load later than onCreate() and it still happens. I also tried adding a 3 second sleep within the for loop of loadData() after each player loads to see if that helped, but no luck.
Am I making bad assumptions? What am I doing wrong and how might I fix it?
I suspect what is happening here is that you are attempting to position views that don't have IDs (it looks like you don't set them anywhere in your code). Dynamically created views don't automatically have IDs, so a call to getId() will return NO_ID (See documentation). If you want to use an ID you will have to set it yourself using View.setId().
It was a timing issue after all. I needed to wait for the main screen to load before I could add views to it. Unfortunately, it would never load until all activity on the UI thread was finished.
Thus, I needed threading. I ended up putting loadData() in a thread, like this:
new Thread(new loadDataAsync(this)).start();
class loadDataAsync implements Runnable {
MainActivity mainActivity;
public loadDataAsync(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public void run() {
try {
Thread.sleep(700);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadData(mainActivity);
}
}
Then I created the players back on the UI thread after the initial sleep to give time for the UI to load.
runOnUiThread(new Runnable() {
Player player;
RelativeLayout mainScreen = (RelativeLayout)findViewById(R.id.relativeLayout);
#Override
public void run() {
player = new Player(savedData.getString("name" + playerNum, null), savedData.getInt("score" + playerNum, 0), playerNum, savedData.getBoolean("enabled" + playerNum, false), mainScreen, presetButtonList, editor, mainActivity);
playerList.add(player);
player.updateScreen();
mainScreen.invalidate();
}
});
Not the most elegant solution, but it works for now.
I'm a novice programmer and I'm trying to learn Android coding using Eclipse.
This is my first time using StackOverflow.
Just for tutorial purposes, I want to make a simple Animal Encyclopedia.
So in my Home class, there are some buttons: "Dog", "Cat", "Bird", etc. When I click the button, it will bring me to the same layout but of course with different content.
So I created a class named AnimalData that holds the
ArrayList<Integer> to store R.drawable.xxx and ArrayList<String>
to store the text that I will put below the picture (like "Bulldog"
or "Husky")
Then I created a class named ChangeContent to set all those drawable
and text to the XML
But whenever I click the button, it results in Stopped Unexpectedly Error
Below are the shortened Home class, The "crash-maker" isn't here. I have checked the whole code line per line using Thread.sleep(2000), so if my app crashes before 2 second, the error is before the sleep() code and vice versa.
public class Home extends Activity implements OnClickListener{
Button dog, cat, bird;
AnimalData ad;
ChangeContent cc;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
//set the findViewById for all the buttons
//set onClickListener() to all the buttons
}
public void onClick(View v) {
switch (v.getId()){
case R.id.bDog:
drawable.add(R.drawable.xxx);
drawable.add(R.drawable.yyy);
title.add("Bulldog");
title.add("Husky");
break;
case R.id.Cat:
//same
break;
case R.id.bBird:
//same
break;
}
ad.setDrawable(drawable);
ad.setTitle(title);
Intent i = new Intent("animal.ChangeContent"); //from Manifest
startActivity(i);
}
}
The AnimalData is just a typical getter setter, so I will just skip the code for that
The error is right after ChangeContent started because even when I put the sleep() on the first line of constructor, it doesn't have any effect.
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
Sorry for the long question, I tried to make it as short as possible
Can you guys help me figure the error out?
Thanks before
You are trying to get arraylist from intent, whereas you are not putting putStringArrayList and putIntegerArrayList methods.
putIntegerArrayListExtra(String name, ArrayList<Integer> value)
putStringArrayListExtra(String name, ArrayList<String> value)
so Change calling activity to following:
Intent i = new Intent(Home.this, ChangeContent.class); //from Manifest
i.putIntegerArrayListExtra("drawables", drawable);
i.putStringArrayListExtra("titles", titles);
startActivity(i);
and get data from intent in onCreate method by following methods:
getIntegerArrayListExtra, and getStringArrayListExtra
you also can do following by making contentChanged method to static, by this you wont need to do much changes in your application code, just do following:
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private static ArrayList<Integer> drawable;
private static ArrayList<String> title;
public static ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
See the answer by RajaReddy P here:
https://stackoverflow.com/a/9937854
In the send class use:
Intent intent = new Intent(PhotoActivity.this,PhotoActivity1.class );
intent.putIntegerArrayListExtra("VALUES", image);
startActivity(cameraIntent);
.. and in the receiver class use:
Intent i = getIntent();
ArrayList<Integer> img = i.getIntegerArrayListExtra("VALUES");
Your approach is wrong -
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
ChangeContent is a Activity class so, you don't pass parameter like this.
Passsing class should be serializable and use it -
startActivity(new Intent(this, ChangeContent.class)
.putExtra("key", ad);
And in your ChangeContent class extract the class from Intent
So, change your code design and go ahead.
Best of luck.