Multiple Activities, launching and passing data - android

I am attempting to create a list of users in an android app. The list is on the MainActivity, with a button which redirects to AddMember. AddMember will take input for one member. I am trying to pass the information back to MainActivity, however it fails before I even get to the AddMemberActivity, when testing. It stops after the button click on the MainActivity.
Trie implementation
The error message is:
java.lang.NullPointerException: Attempt to invoke virtual method 'char java.lang.String.charAt(int)' on a null object reference
at attendance.Trie.get(Trie.java:117)
at attendance.Trie.get(Trie.java:113)
at attendance.MainActivity$1.onClick(MainActivity.java:49)
line 49 is
if (trie.get(name) != null) {
public class MainActivity extends AppCompatActivity {
private Button button;
private ListView list;
private Trie trie;
private ArrayAdapter<String> adapter;
private int count = 0;
private static final int REQUEST_CODE = 100;
private String name;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if(resultCode == RESULT_OK) {
name = data.getStringExtra("name");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.addBtn);
list = (ListView) findViewById(R.id.memberList);
trie = new Trie();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddMember.class);
startActivityForResult(intent, REQUEST_CODE);
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.content_list_items,R.id.list_content, trie.traverse());
list.setAdapter(adapter);
//check that member was added
if (trie.get(name) != null) {
// <- look for item!
//made an alert to show member already exists
} else {
trie.put(name.toLowerCase(), count++);
adapter.add(name);
}
adapter.notifyDataSetChanged();
}
});
}
}
public class AddMember extends AppCompatActivity {
//Array of options --> ArrayAdapter --> ListView
//ListView :{views, items.xml}
private static final int REQUEST_CODE = 100;
private Button button;
private EditText name;
private EditText phone;
private EditText email;
private ArrayAdapter<Member> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_member);
button = (Button) findViewById(R.id.uploadMember);
name = (EditText) findViewById(R.id.edit_name);
//add member button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("name", name.getText());
setResult(RESULT_OK, intent);
finish();
}
});
}
}

It is clear from crash log that you are attempting to get character from null string .
java.lang.String.charAt(int)' on a null object reference at attendance.Trie.get(Trie.java:117)
Reason : You are passing null value in get method. You never assign the name string and by default it is assigned with null. And you pass it with trie.get(name).
Check your get method of Trie class and put a check of null. If name is not null then get the character from string otherwise return null.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
if(resultCode == RESULT_OK) {
name = data.getStringExtra("name");
if(adapter == null){
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.content_list_items,R.id.list_content, trie.traverse());
list.setAdapter(adapter);
}
//check that member was added
if (trie.get(name) != null) {
// <- look for item!
//made an alert to show member already exists
} else {
trie.put(name.toLowerCase(), count++);
adapter.add(name);
}
adapter.notifyDataSetChanged();
}
}
}
Remove adapter code from onClick method
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddMember.class);
startActivityForResult(intent, REQUEST_CODE);
});

Related

Need to know where to correctly place the finish() function to close an activity

I am stuck trying to figure out where exactly to put the finish() function in my code.
I have tried putting it on line 43 of ProfileActivity or lines 39 or 56 of MainActivity. I'm very new at this and have read what the purpose of finish() is but can't figure out where else in my code it should go.
These are just nippets of the code ... there is more (all the Activity lifecycle functions), but I omitted to save space.
public class MainActivity extends AppCompatActivity {
SharedPreferences sp;
EditText email;
public static final String ACTIVITY_NAME = "PROFILE_ACTIVITY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText)findViewById(R.id.thisEmailIsPassedToPage2);
sp = getSharedPreferences("Lab3", Context.MODE_PRIVATE);
String savedString = sp.getString("Email", "0");
email.setText(savedString);
Log.e(ACTIVITY_NAME, "In Function onCreate() in MainActivity:");
Button login = (Button)findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
ProfileActivity.class);
EditText et =
(EditText)findViewById(R.id.thisEmailIsPassedToPage2);
intent.putExtra("typed", et.getText().toString());
startActivityForResult(intent, 2);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
int i = 0;
i++;
//if request code is 2, then we are coming back from ProfileActivity
if(requestCode == 2){
EditText et =
(EditText)findViewById(R.id.thisEmailIsPassedToPage2);
String fromProfile = data.getStringExtra("typed");
et.setText(fromProfile);
Log.i("Back", "Message");
}
}
public class ProfileActivity extends AppCompatActivity {
private SharedPreferences sp;
private ImageButton mImageButton;
public static final String ACTIVITY_NAME = "PROFILE_ACTIVITY";
public static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profileactivity);
Log.e(ACTIVITY_NAME, "In Function onCreate() in ProfileActivity:");
Intent fromPrevious = getIntent();
String previousTyped = fromPrevious.getStringExtra("typed");
EditText enterText = (EditText) findViewById(R.id.editText6);
enterText.setText(previousTyped);
mImageButton = (ImageButton) this.findViewById(R.id.imageButton);
mImageButton.setOnClickListener(bt -> {
dispatchTakePictureIntent();
});
}
private void dispatchTakePictureIntent(){
Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageButton.setImageBitmap(imageBitmap);
}
}
These are the screenshots:
[MainActivity1stPage][1]
[ProfileActivity2ndPage][2]
[AfterImageButtonPressed][3]
[AfterTakingPictureAndPressingOK][4]
If I'm getting it right, your flow is MainActivity starts ProfileActivity for result, then in ProfileActivity you start the ACTION_IMAGE_CAPTUREfor result, so I'm guessing that with that result you want to trigger your MainActivity onActivityResult. So if that the case you need to setResult and finish at the onActivityResultof your ProfileActivity.

Android RecyclerView does not refresh after insert

I have a problem with my RecyclerView.
I have a ProductDetailActivity which shows the detail of a product and i have a RecyclerView with its adapter in it.
The user can click on the give rating button which navigates to the RatingActivity where you can give a rating to the product.
The problem is that when i submit my rating and automatically go back to my RatingActivity, the RecyclerView does not get the recently added rating. i have to go back to my productlist and reclick on the product to see the recently added rating.
Here is my code:
ProductDetailActivity:
public class ProductDetailActivity extends AppCompatActivity {
public AppDatabase appDatabase;
private static final String DATABASE_NAME = "Database_Shop";
private RecyclerView mRecycleviewRating;
private RatingAdapter mAdapterRating;
private Button btnGoToRatingActivity;
List<Rating> ratings;
Product p;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
appDatabase = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
btnGoToRatingActivity = findViewById(R.id.btn_goToRatingActivity);
Intent intent = getIntent();
id = intent.getIntExtra("productid", -1);
// pour montrer tous les ratings d'un produit, tu fais un getall
p = appDatabase.productDAO().getProductById(id);
ImageView imageView = findViewById(R.id.imageDetail);
TextView textViewName = findViewById(R.id.txt_nameDetail);
TextView textViewAuthor = findViewById(R.id.txt_authorDetail);
TextView textViewCategory = findViewById(R.id.txt_categoryDetail);
TextView textViewDetail = findViewById(R.id.txt_descriptionDetail);
Picasso.get().load(p.getProductImage()).fit().centerInside().into(imageView);
textViewName.setText(p.getProductName());
textViewAuthor.setText(p.getProductAuthor());
textViewCategory.setText(p.getProductCategory());
textViewDetail.setText(p.getProductDescription());
ratings = appDatabase.ratingDAO().getRatingByProductId(id);
mRecycleviewRating = findViewById(R.id.recyclerRating_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecycleviewRating.setLayoutManager(linearLayoutManager);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapterRating = new RatingAdapter(ratings);
mRecycleviewRating.setAdapter(mAdapterRating);
btnGoToRatingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ProductDetailActivity.this, RatingActivity.class);
i.putExtra("productid", p.getProduct_id());
startActivity(i);
}
});
mAdapterRating.notifyDataSetChanged();
}
#Override
public void onResume() {
super.onResume();
ratings = appDatabase.ratingDAO().getRatingByProductId(id); // reload the items from database
mAdapterRating.notifyDataSetChanged();
System.out.println(mAdapterRating.ratings.size());
}
}
RatingActivity:
public class RatingActivity extends AppCompatActivity implements RatingGiveFragment.RatingListener {
RelativeLayout mRelativeLayout;
private Button btnConfirmRating;
private EditText mComment;
private RatingBar mRatingBar;
public AppDatabase appDatabase;
private RatingAdapter mAdapter;
List<Rating> ratings;
private static final String DATABASE_NAME = "Database_Shop";
Product p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
appDatabase = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
int idProduct = RatingActivity.this.getIntent().getIntExtra("productid",-1);
p = appDatabase.productDAO().getProductById(idProduct);
mRatingBar = findViewById(R.id.rating_bar);
mComment = findViewById(R.id.txt_insertOpinionText);
mRelativeLayout = findViewById(R.id.activity_rating);
btnConfirmRating = findViewById(R.id.buttonConfirmRating);
mAdapter = new RatingAdapter(ratings);
btnConfirmRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkEmptyFields()) {
Rating rating = new Rating(p.getProduct_id(),UserConnected.connectedUser.getUser_id(),mRatingBar.getRating(), UserConnected.connectedUser.getUsername(), mComment.getText().toString());
appDatabase.ratingDAO().insertRating(rating);
mAdapter.notifyDataSetChanged();
finish();
}else{
Toast.makeText(RatingActivity.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
});
}
/*private class insertRating extends AsyncTask<String,Integer, Integer>
{
#Override
protected Integer doInBackground(String... strings) {
Rating rating = new Rating(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]), Integer.parseInt(strings[2]), strings[3], strings[4]);
appDatabase.ratingDAO().insertRating(rating);
return 1;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (integer == 1)
{
Toast.makeText(getApplicationContext(), getString(R.string.createRating), Toast.LENGTH_SHORT).show();
}
}
}*/
#Override
public void ratingChanged(int newRating) {
RatingTextFragment textFragment = (RatingTextFragment) getSupportFragmentManager().findFragmentById(R.id.fmt_text);
textFragment.setRating(newRating);
}
private boolean checkEmptyFields(){
if(TextUtils.isEmpty(mComment.getText().toString())){
return true;
}else{
return false;
}
}
}
RatingAdapter:
public class RatingAdapter extends RecyclerView.Adapter<RatingAdapter.RatingViewHolder> {
List<Rating> ratings;
public RatingAdapter(List<Rating> ratings){
this.ratings = ratings;
}
#NonNull
#Override
public RatingViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rating_row,viewGroup, false);
return new RatingViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RatingViewHolder ratingViewHolder, int position) {
ratingViewHolder.ratingUsername.setText(ratings.get(position).getRatingUsername());
ratingViewHolder.ratingNumber.setText(String.valueOf(ratings.get(position).getRatingNumber()) + "/5");
ratingViewHolder.ratingComment.setText(ratings.get(position).getRatingText());
}
#Override
public int getItemCount() {
return ratings.size();
}
public static class RatingViewHolder extends RecyclerView.ViewHolder{
public TextView ratingUsername;
public TextView ratingNumber;
public TextView ratingComment;
public RatingViewHolder(#NonNull View itemView) {
super(itemView);
ratingUsername = itemView.findViewById(R.id.txt_usernamerating);
ratingNumber = itemView.findViewById(R.id.num_rating);
ratingComment = itemView.findViewById(R.id.txt_ratingComment);
}
}
}
Pictures:
You get no update in the ProductDetailActivity because you are not updating the data object ratings in the ProductDetailActivity that is the basis for the RatingAdapter.
It would be better to use startActivityForResult in the onClick()method of the ProductDetailActivity. Then you need to override the onActivityResult() method in the ProductDetailActivity. Evaluate the return values and update your data source if necessary, then call notifyDataSetChanged.
This is just pseudo code!
Changes to ProductDetailActivity:
btnGoToRatingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ProductDetailActivity.this, RatingActivity.class);
i.putExtra("productid", p.getProduct_id());
// with this you are telling the activity to expect results and..
//..to deal with them in onActivityResult
startActivityForResult(i, 1);
}
});
// You do not need this next line because setting the adaper triggers the first
//mAdapterRating.notifyDataSetChanged();
}
Add the onActivityResult() method to the ProductDetailActivity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
// trigger a method to update the data object that is linked to the adapter
ratings = appDatabase.ratingDAO().getRatingByProductId(id);
// and now that the data has actually been updated you can call notifyDataSetChanged!!
mAdapterRating.notifyDataSetChanged();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Probably do nothing or make a Toast "Canceled"??
}
}
}
Changes to RatingActivity:
btnConfirmRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkEmptyFields()) {
// I will just assume this works!
Rating rating = new Rating(p.getProduct_id(),UserConnected.connectedUser.getUser_id(),mRatingBar.getRating(), UserConnected.connectedUser.getUsername(), mComment.getText().toString());
appDatabase.ratingDAO().insertRating(rating);
Intent intent = new Intent();
//If you need to return some value.. do it here other you do not need it
//intent.putExtra("result", result);
setResult(Activity.RESULT_OK, intent);
finish();
}else{
Toast.makeText(RatingActivity.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
});
Please be aware in RatingActivity that in btnConfirmRating.setOnClickListener notifying the adapter with mAdapter.notifyDataSetChanged(); does nothing: firstly, because the adapter in the RatingActivity has nothing to do with the adapter in the ProductDetailActivity; secondly: you call finish(); in the next line of code.

Invoking camera from within my application through button click

Completely new to this and to Android development, looking for a bit of help if possible. I am developing my first application for Android at the moment and have very little coding experience...I basically have an application at the moment that is allowing me to add/delete/update users to and from a sqlite database. I am looking for a way just to add a button on the main homepage that allows me to access the camera and take a picture. The main activity is simply a page with buttons to add/delete etc:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("Please enter a name!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("User Added!");
} else {
toastMessage("Something went wrong");
}
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
The code I have for implementing the camera is shown below(it works for invoking the camera and taking a picture but only from the camera outside the application)
Is it possible for me to just a button on the main activity page that allows me to "take picture" from within the application
(code for invoking camera)
public class MainActivity extends AppCompatActivity {
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager. PERMISSION_GRANTED){
getPhoto();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else{
getPhoto();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
try {
Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sorry if the question seems stupid, completely new to Android development and new to coding so I am very unsure.
I'm not sure about what you are looking for, but here is code to take a picture :
https://developer.android.com/training/camera/photobasics.html
To add the button, you need to add it in the layout then get the reference in your activity class with the findViewById method
Hope this help

I have error when use context in adapter, i would like use startActivityForResult(...) in adapter, how should I do?

and thank you in advance for your suggestions.
MainActivity.java
RecyclerView.Adapter mAdapter;
#Override
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mAdapter = new MyAdapter(getBaseContext(),TITLES,ICONS,NAME,EMAIL,PROFILE);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
...}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
String path = "";
mImageCaptureUri = data.getData();
path = getPath(mImageCaptureUri); //from Gallery
if (path == null)
path = mImageCaptureUri.getPath();
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
mImageView.setImageBitmap(bitmap);
}
Myadapter.java
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
...
Context mContext;
Activity mActivity;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
public static class ViewHolder extends RecyclerView.ViewHolder {...}
MyAdapter(Context context, String Titles[],int Icons[],String Name,String Email, int Profile){
this.mContext = context;
mNavTitles = Titles
mIcons = Icons;
name = Name;
email = Email;
profile = Profile;
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
if(holder.Holderid ==1) {
holder.textView.setText(mNavTitles[position - 1]);
holder.imageView.setImageResource(mIcons[position -1]);
}
else{
holder.profile.setImageResource(profile);
holder.Name.setText(name);
holder.email.setText(email);
holder.profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity = (Activity)mContext;
Intent imageIntent = new Intent();
imageIntent.setType("image/*");
imageIntent.setAction(imageIntent.ACTION_GET_CONTENT);
mActivity.startActivityForResult(Intent.createChooser(imageIntent, "Select photo"), 2);
}
});
}
}
It's possible call startActivityForResult in Adapter?
Why error is on mActivity = (Activity)mContext;?
p.s.: I tried to create method
public void startxx(Intent i){
startActivityForResult(i, 2);
}
and call this in Adapter...but Adapter wants statxx static and Activity non-static.
Context is Base class for Activity. You can not downcast object in Java. Thats why you can not perform mActivity = (Activity)mContext;.
You can not call startActivityForResult() from as Adapter class as it is method of Activity.java class. Here is one solution you can try -
- Declare one interface. say IObserver.java
public interface IObserver {
// change signature of method as per your need
public abstract void onItemClicked();
}
}
Write one method in Adapter class say
public void setListener(IObserver obs) {
mObserver = obs;
}
Implement IObserver interface in Activity class. You need to implement onItemClicked() method as well.
From onCreate() method of activity, call adapter.setListener(this);
In adapter class, from onClick() method, write code as below
holder.profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// It will call method from activity class where you can do startActivityForResult()
mObserver.onItemClicked();
}
});
Hope it will help.

onActivityResult not getting string out of Intent

I need some help with my android app. I have two activities, first starts the second one with startActivityForResult(). When the second one closes it sends the intent as it should, however when i want to access extra from onActivityResult() i get a null instead of what I put in.
I also tried using bundle with
Bundle b = getIntent().getExtras();
b.getString(AddTable.EXTRA_NAME);
but it resulted in RuntimeException and failure delivering result.
Here's my code:
public class RunnerApp extends Activity {
private ListView listView;
private static ArrayList<String> values = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private Intent newTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_app);
listView = (ListView) findViewById(R.id.mylist);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
public void addTable(View v){
newTable = new Intent(this, AddTable.class);
startActivityForResult(newTable, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK && data != null){
data = getIntent();
Log.d("add", "got intent");
String newName = data.getStringExtra(AddTable.EXTRA_NAME);
Log.d("add", "string " + newName); //always prints string null
values.add(newName);
Log.d("add", "added to list");
}
}
#Override
public void onResume(){
super.onResume();
setContentView(R.layout.activity_runner_app);
adapter.notifyDataSetChanged();
}
}
Second activity started by startActivityForResult()
public class AddTable extends Activity {
public final static String EXTRA_NAME = "com.example.runnerapp.NAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_table);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_add_table, menu);
return true;
}
public void addThisTable(View v) {
Intent addTable = new Intent(this, RunnerApp.class);
EditText editText = (EditText) findViewById(R.id.addTableField);
String name = editText.getText().toString();
addTable.putExtra(EXTRA_NAME, name);
Log.d("intenyt", name);
setResult(Activity.RESULT_OK, addTable);
this.finish();
}
}
In your first activity your code reads
data = getIntent();
But the actual data you want is in
data.getData()
use this in the onActivityResult function..
data.getStringExtra(EXTRA_NAME)

Categories

Resources