android: null pointer exception when trying to set any property of button - java

i have checked everything in this but still i am getting a null pointer exception . whenever i am trying to change the properties of button in java file, app stop working and logcat showing null pointer exception. plzz help me out
here is my code
package com.example.rapid_finger;
import java.util.Random;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class PlayScreen extends Activity {
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Random rand = new Random();
int data = rand.nextInt(99);
String str = Integer.toString(data);
Button b = (Button) findViewById(R.id.b1);
b.setText(str);
setContentView(R.layout.activity_play_screen);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.play_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up- vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here is my xml file
<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=".PlayScreen" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/scores" />
<Button
android:id="#+id/b1"
android:background="#drawable/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>

You did findViewById before you setContentView.
setContentView should come first

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
Random rand = new Random();
int data = rand.nextInt(99);
String str = Integer.toString(data);
Button b = (Button) findViewById(R.id.b1);
b.setText(str);
// Show the Up button in the action bar.
setupActionBar();
}
put setContentView(R.layout.activity_play_screen); after super.onCreate(savedInstanceState);

// replace this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
Random rand = new Random();
int data = rand.nextInt(99);
String str = Integer.toString(data);
Button b = (Button) findViewById(R.id.b1);
b.setText(str);
// Show the Up button in the action bar.
setupActionBar();
}

Related

Android bluetooth app crashing on startup

When the app first starts it immediately crashes on startup. I have narrowed down the problem to one line but not really sure what to do =/ here are the two classes in the app so far:
package com.example.bluetooth_app;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Bluetooth {
private BluetoothAdapter mBluetoothAdapter;
private Activity activity; //Activity to store main window's activity
private ArrayAdapter<String> pDevices; //Array adapter for storing already paired devices
private ArrayAdapter<String> nDevices; //Array adapter for storing newly discovered devices
private IntentFilter filter; //Filter for catching bluetooth device actions
private Button sButton; //Scan button
private ListView lvBox; //listview box
/**
* default constructor, basic initializations
*/
public Bluetooth(Activity activity) {
this.activity = activity; //Set class activity to the activity passed to it by the main activity window
pDevices = new ArrayAdapter<String>(activity, R.layout.activity_bluetooth__app);
nDevices = new ArrayAdapter<String>(activity, R.layout.activity_bluetooth__app);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
sButton = (Button) activity.findViewById(R.id.scanButton); //sButton = scan button
sButton.setOnClickListener(new View.OnClickListener() { //Listener to check if button is pressed
public void onClick(View v) { //If button is pressed start discovering and hide button
startDiscovering();
sButton.setVisibility(4); //Make button invisible
}
});
lvBox = (ListView) activity.findViewById(R.id.deviceList); // lvBox = deviceList listview
lvBox.setAdapter(pDevices);
// Register for broadcasts when a device is discovered
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
activity.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
activity.registerReceiver(mReceiver, filter);
}
/**
* Check if bluetooth is enabled, if not enable it
*/
public void getAdapter() {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(enableBtIntent, 1);
}
}
/**
* Check if device is bluetooth compatible
*/
public boolean isCompat() {
if(mBluetoothAdapter == null) {
return false; //TODO: better error handling
} else {
return true;
}
}
/**
* Close some shit so we do not eat up resources
*/
public void destroy() {
if(mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery(); //cancel discovering devices
}
activity.unregisterReceiver(mReceiver);
}
/**
* Start discovering devices with bluetooth adapter
*/
public void startDiscovering() {
if(mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
}
public void pairedDevices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
sButton.setText("found some");
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
pDevices.add(device.getName() + "\n" + device.getAddress());
}
}
}
/**
* The BroadcastReceiver that listens for discovered devices and changes the title when
* discovery is finished
*/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
nDevices.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
sButton.setVisibility(0); //Make button visible again
if (nDevices.getCount() == 0) {
sButton.setText("none");
//TODO: none found do something
}
}
}
};
}
and:
package com.example.bluetooth_app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.example.bluetooth_app.Bluetooth;
public class Bluetooth_App extends ActionBarActivity {
private Bluetooth bT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth__app);
bT = new Bluetooth(this);
bT.isCompat();
bT.getAdapter();
bT.pairedDevices();
}
#Override
protected void onDestroy() {
super.onDestroy();
bT.destroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bluetooth__app, 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);
}
}
The problem is in the first class, this line: lvBox.setAdapter(pDevices);,if I comment it out it runs just fine, if not it crashes on startup. Any help would be appreciated - thanks.
EDIT1 - no it has a listview called deviceList, XML file:
<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="com.example.bluetooth_app.Bluetooth_App" >
<Button
android:id="#+id/scanButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="28dp"
android:layout_marginTop="21dp"
android:text="Scan" />
<ListView
android:id="#+id/deviceList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginRight="26dp"
android:layout_marginTop="48dp" >
</ListView>
</RelativeLayout>
Note that you seem to be reusing your activity's layout file R.layout.activity_bluetooth__app when initializing your ArrayAdapters in Bluetooth_App. This is probably not what you meant to do. The resource passed to the ArrayAdapter constructors should represent the layout of a single AdapterView row, and must contain a TextView with id text1 (to use a more customized row layout, you would need to subclass ArrayAdapter and override getView).

Android App OnClick Crashing

So i have a simple app, just a menu with a few buttons, when a button is clicked you are brought to a new page. The page has a button, which when clicked, keeps changing its background image until it runs out of images (list of image names stored in strings), then you are brought back to the main menu. I can do this twice, then on the third attempt, if i click a button on the menu the app crashes. This doesnt happen on the emulator, only when i run it on my phone. I dont know why this is happening
package com.example.otapp;
import com.example.otapp.R.raw;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.media.MediaPlayer;
public class MainActivity extends ActionBarActivity {
public static String DPExtension;//Holds the letters dp
public String list;
public static int Screen_Height;//holds screen height
public static int Screen_Width;//holds screen width
public Intent intent;
public MediaPlayer audio;
public final static String EXTRA_MESSAGE = "com.example.otapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this code block is for getting the screen proportions
Display getdisplay = getWindowManager().getDefaultDisplay();
DisplayMetrics dispMetrics = new DisplayMetrics();
getdisplay.getMetrics(dispMetrics);
float densitydp = getResources().getDisplayMetrics().density;
float ScreenHeightdp = dispMetrics.heightPixels / densitydp;
float ScreenWidthdp = dispMetrics.widthPixels / densitydp;
//Below dimension value holders do not use pixel density
float ScreenHeightCheck = dispMetrics.heightPixels;
float ScreenWidthCheck = dispMetrics.heightPixels;
DPExtension = "dp";
Screen_Height = (int) ScreenHeightCheck;
Screen_Width = (int) ScreenWidthCheck;
//The printlns are so I can discern the outputs in LogCat
//System.out.println("Screen Height:" + Screen_Height);
//System.out.println("Screen Width:" + Screen_Width);
View Button1 = findViewById(R.id.Button01);
LinearLayout.LayoutParams params = (LayoutParams) Button1.getLayoutParams();
params.height = Screen_Height/3;
Button1.setLayoutParams(params);
View Button2 = findViewById(R.id.Button02);
Button2.setLayoutParams(params);
View Button3 = findViewById(R.id.Button03);
Button3.setLayoutParams(params);
View Button4 = findViewById(R.id.Button04);
Button4.setLayoutParams(params);
Button1.setOnClickListener(onClickListener);
Button2.setOnClickListener(onClickListener);
Button3.setOnClickListener(onClickListener);
Button4.setOnClickListener(onClickListener);
Button1.setBackgroundResource(getResources().getIdentifier("gettingup", "drawable", getPackageName()));
intent = new Intent(this, DisplayMessageActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
audio = MediaPlayer.create(MainActivity.this, raw.buttonsound);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// play sound
audio.start();
// do different things for each different button
switch(v.getId()) {
case R.id.Button01:
list = "Get Up";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button02:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button03:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button04:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
}
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:background="#1E90FF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/Button01"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button_send"/>
<Button
android:id="#+id/Button03"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button2_send" />
<Button
android:id="#+id/Button04"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button3_send" />
<Button
android:id="#+id/Button02"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button4_send" />
</LinearLayout>
</ScrollView>
If the source above is formatted correctly, line 99, which is where the NullPointerException is thrown, is:
audio.start();
This means that audio is null. It is declared on line 83:
audio = MediaPlayer.create(MainActivity.this, raw.buttonsound);
Most likely what's happening is that the MediaPlayer.create is unable to located the raw.buttonsound. I'd debug at this line and verify that the MediaPlayer is failing to create the audio.
Try moving the definition of the onClickListener object into the onCreate method.
You can declare it as a member variable, but you should create the object and assign it to the field in onCreate()

How long the activity was open?

I'm new in android programming and I'm making a very simple app.
I only have one text view and one button, and when I click the button I want to show in the text view a value that represents how long the activity was open.
this is my xml file:
<Button
android:id = "#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button"
android:layout_centerHorizontal="true"
android:text=" " />
</RelativeLayout>
and this is my java file:
package com.diogoc.teste;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(Listener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private OnClickListener Listener = new OnClickListener() {
public void onClick(View v) {
//It's here
textView.setText("You take");
}
};
}
Thank you.
Add this member variable to the class:
long startTime;
Add this to your onCreate()-method:
startTime = System.currentTimeMillis();
Add this to your onClick()-method:
long timeElapsedMS = System.currentTimeMillis()-startTime; //gets the time difference in milliseconds
long timeElapsedSeconds = timeElapsedMS/1000;
textView.setText("You took "+timeElapsedSeconds+" seconds");
Something like this in your onCreate will work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Other stuff omitted */
final long start= System.currentTimeMillis();
final Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
textView.setText(System.currentTimeMillis() - start);
handler.postDelayed(this, 100);
}
}, 100);
}
The code in the run() method will run indefinately every 100 ms, updating the text in your textview with the milliseconds passed since the call to onCreate().

setOnClickListener in TextView

I'm trying to build an text view that goes to onClick but its not working they told me to add this code I did it but I'm having a lot of errors in it.
this is my MainActivity.java
package imamalsajadsayings.android.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void runNextTask(){
final View addView = getLayoutInflater().inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
//set up for model selection
TextView modelTextview = (TextView)addView.findViewById(R.id.state1);
modelTextview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and is my textview
<TextView
android:id="#+id/state1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Tracker_model"
android:clickable="true"
note : I don't have addnewtracker created
errors :
Description Resource Path Location Type
TrackerInfo cannot be resolved to a type MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 20 Java Problem
addnewtracker cannot be resolved or is not a field MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 19 Java Problem
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new OnClickListener(){}) MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 23 Java Problem
TrackerInfo cannot be resolved to a type MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 20 Java Problem
The method onClick(View) of type new OnClickListener(){} must override or implement a supertype method MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 25 Java Problem
OnClickListener cannot be resolved to a type MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 23 Java Problem
add to activity:
public void modelTextViewClick(View v) {
//do something on click
}
and to layout:
<TextView android:id="#+id/state1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Tracker_model"
android:clickable="true"
android:onClick="modelTextViewClick"/>
and remove your on click listener.
Change below code to your XML file
<TextView android:id="#+id/state1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Tracker_model"
android:clickable="true"
android:onClick="runNextTask"/>
and just modify your java file as follow.
public void runNextTask(View v){
final View addView = getLayoutInflater().inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
//set up for model selection
TextView modelTextview = (TextView)addView.findViewById(R.id.state1);
modelTextview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
you need to import this package to avoid this error
missing this -> import android.view.View.OnClickListener;
Use below piece of code.
package imamalsajadsayings.android.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void runNextTask(){
final View addView = getLayoutInflater().inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
//set up for model selection
TextView modelTextview = (TextView)addView.findViewById(R.id.state1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void modelTextViewClick(View view)
{
// here view reference is your text view reference.
// put your on click handler code.
}
}
difference between this code and your code is onclick handler. In xml you have already defined a on click handler which you have to use in activity code. Other way set onclick listener handler foe your widget. Your doing both but either one of them is allowed not both for any widget in android.
You haven't call runNextTask from ur onCreate()
u r inflating a layout but didn't add that layout in any layout of ur activity_main layout using addView method
thats why it didn't work
it should be
package imamalsajadsayings.android.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
private LayoutInflater inflater;
private LinearLayout someLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
someLayout = (LinearLayout) findViewById(R.id.some_layout); //layout present in activity_main
inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
runNextTask();
}
public void runNextTask(){
LinearLayout mInflatedLayout = (LinearLayout) inflater.inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
//set up for model selection
TextView modelTextview = (TextView)mInflatedLayout.findViewById(R.id.state1);
someLayout.addView(mInflatedLayout);
modelTextview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Assuming u r using LinearLayout in ur activity_main layout

Android Parcelable object not passing properly between activities

This has been taxing my mind for the past two days. Oddly, the code works fine in one project, when passing an object from activity to fragment, but I cannot make this object pass from activity to activity, even when I appear to be implementing parcelable properly.
Oddly, I don't get a null object at the other end, but the object has got null values within it.
I've created a new project to test this with. This is the code so far:
MainActivity.java:
package com.example.parcleableexample;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
Site mySite = new Site();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySite.setSiteName("hi");
TextView myText = (TextView) findViewById(R.id.txtSiteName);
myText.setText(mySite.getSiteName());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void doThing (View v) {
Intent mIntent = new Intent(this,AnotherActivity.class);
mIntent.putExtra("site", mySite);
startActivity(mIntent);
}
}
AnotherActivity.java:
package com.example.parcleableexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class AnotherActivity extends Activity {
Site mySite = new Site();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySite = getIntent().getParcelableExtra("site");
TextView myText = (TextView) findViewById(R.id.txtSiteName);
myText.setText(mySite.getSiteName());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Site.Java:
package com.example.parcleableexample;
import android.os.Parcel;
import android.os.Parcelable;
public class Site implements Parcelable {
private String siteName;
Site() {
// Empty Constructor
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
// Parcleable Functions:
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<Site> CREATOR = new Parcelable.Creator<Site>() {
public Site createFromParcel(Parcel in) {
return new Site(in);
}
public Site[] newArray(int size) {
return new Site[size];
}
};
private Site(Parcel in) {
mData = in.readInt();
}
}
activity_main.xml:
<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=".MainActivity" >
<TextView
android:id="#+id/txtSiteName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtSiteName"
android:layout_below="#+id/txtSiteName"
android:layout_marginLeft="42dp"
android:layout_marginTop="25dp"
android:onClick="doThing"
android:text="Button" />
</RelativeLayout>
What I would expect, is for the "hi" value to appear both times, once when I start the app, and again when I click the button and the new activity creates.
However, it's only showing correctly the first time, the second time the getSiteName only returns null.
I also copied and pasted the Site object directly from the working app, with the same result, but it works in the working app as expected; the Site object is copied properly.
The working app runs this code:
Bundle arguments = new Bundle();
arguments.putParcelable("site", SearchResults.get(position));
ViewSiteFragment myFragment = new ViewSiteFragment();
myFragment.setArguments(arguments);
FragmentTransaction myTransaction = getFragmentManager().beginTransaction();
myTransaction.replace(R.id.MainFragmentContainer, myFragment);
myTransaction.addToBackStack(null);
myTransaction.commit();
And picks up the object at the other end here:
Site mSite = getArguments().getParcelable("site");
I know I'm doing something wrong... Just haven't got a clue what I've missed!
The problem is in your implementation of Parcelable. siteName is never written to the parcel, and you are writing mData instead, which is never used anywhere. You can keep mData if you need it, and ADD writes for siteName, see the code:
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
//we want to keep siteName in our parcel, so let's write it to the Parcel obj
out.writeString(siteName);
}
Later, add this code to read from parcel:
private Site(Parcel in) {
mData = in.readInt();
//let's read from in Parcel an set our siteName
siteName = in.readString();
}
Receive it like this with bundle object:
In activity2, in onCreate(), you can get the String message/object by retrieving a bundle (which contains all the messages sent by the calling activity) and call:
Bundle bundle = getIntent().getExtras();
mySite = bundle.getParcelableExtra("site");

Categories