onActivityResult not getting string out of Intent - android

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)

Related

In onActivityResult i am getting null value from received intent

I have two activities: A and B.
In activity A: On "btn_navSimilarColor" buttonClick - I made a call to B with startActivityForResult. There are already some intents inside A to use camera and gallery and a intent data i am receiving from previous activity.
In activity B: I made a asyncTask call inside onCreate() and in asyncTask's onPostExecute() i am sending back intent extra to Activity A.
Activity A:
public class A extends Activity
{
...
#Override
public void onCreate(Bundle savedInstanceState)
{
...
Bundle extras = getIntent().getExtras();
if (extras != null) {
edtTxtColorCode.setText(extras.getString("xtra_selectedColor"));
} else {
Toast.makeText(this, "There was a problem in the response!", Toast.LENGTH_SHORT).show();
}
}
public void buttonOnClick(View view)
{
switch (view.getId())
{
case R.id.btnCamera:
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), FLAG_CAMERA);
break;
case R.id.btnGallery:
startActivityForResult(
new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI), FLAG_GALLERY);
break;
case R.id.btn_navSimilarColor:
Intent intnt_similar = new Intent(A.this, B.class);
intnt_similar.putExtra("xtraColor", edtTxtColorCode.getText().toString());
startActivityForResult(intnt_similar, FLAG_navSimilarColorAct);
break;
default:
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.v("resultCode","="+resultCode);
if (resultCode == Activity.RESULT_OK)
{
mCursor = null;
if (requestCode == FLAG_GALLERY)
onSelectFromGalleryResult(data);
else if (requestCode == FLAG_CAMERA)
onCaptureImageResult(data);
else if(requestCode == FLAG_navSimilarColorAct)
{ Bundle extras = getIntent().getExtras();
String stt = extras.getString("intnt_similarColor");
if (extras != null)
edtTxtColorCode.setText(extras.getString("intnt_similarColor"));
}
}
}
}
Activity B:
public class B extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
....
receiveIntent();
new AsyncConver().execute();
}
private void receiveIntent() {
Bundle extras = getIntent().getExtras();
if (extras != null)
strIntentrecvdColor = extras.getString("xtraColor");
else
Toast.makeText(this, "There was a problem in the response!", Toast.LENGTH_SHORT).show();
}
class AsyncConvert extends AsyncTask<String, Integer, String>
{
...
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
Custom_SimilarColorListAdapter gridAdapter = new Custom_SimilarColorListAdapter(SimilarColors.this, list_SimilarColors);
grdVw.setAdapter(gridAdapter);
grdVw.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String str_colorCodeSimilar = ((TextView) v.findViewById(R.id.listrow_similar_code)).getText().toString();
Toast.makeText(getApplicationContext(), "ID:: "+ str_colorCodeSimilar , Toast.LENGTH_SHORT).show();
Intent retrnIntnt = new Intent();
retrnIntnt.putExtra("intnt_similarColor", str_colorCodeSimilar);
setResult(RESULT_OK, retrnIntnt);
finish();
}
});
}
}
}
Problem:
Now the problem is that i am getting data in activity B - as i am already checking it with
Toast.makeText(getApplicationContext(), "ID:: "+ str_colorCodeSimilar , Toast.LENGTH_SHORT).show();
But in Activity A's onActivityResult i am not getting the bundle extra data for "intnt_similarColor" which is:
String stt = extras.getString("intnt_similarColor");
instead i am getting bundle extra for "xtra_selectedColor" which is inside onCreate().
Why is this happening and how am i getting the previous bundle data , not the one that has been passed from activity B?
change Bundle extras = getIntent().getExtras(); to Bundle extras = data.getExtras();
Get string from data intent that you receive from onActivityResult. You use Bundle extras = getIntent().getExtras(); where getIntent() is actually class A's received intent.
So you have to use:
String stt = data.getStringExtra("intnt_similarColor");

Multiple Activities, launching and passing data

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);
});

getIntent() doesn't retrieve previous activity's intent and return null

I am trying to post in an ArrayList of strings from one activity to another when the option menu is pressed. However, when I try to getIntent() in the next page, it returns null value.
Option menu when item is selected code:
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==2){
ArrayList<String>data1=new ArrayList<>();
data1.add("Hello");
data1.add("bye");
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("dataList",data1);
startActivity(i);
}
return true;
}
Retrieve Data Activity :
public class SecondActivity extends AppCompatActivity {
ListView lListView;
ArrayAdapter<String> adapter;
Intent intent = getIntent();
ArrayList<String> data = intent.getStringArrayListExtra("dataList");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
lListView = (ListView)findViewById(R.id.lListView);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
lListView.setAdapter(adapter);
}
}
Intent intent = getIntent();
ArrayList<String> data = intent.getStringArrayListExtra("dataList");
add this lines in oncreate
Move this code into your onCreate method:
Intent intent = getIntent();
ArrayList<String> data = intent.getStringArrayListExtra("dataList");
Intent does not exist at the point that you try to get it, it is being passed later in your activity's lifecycle. That is why you are getting null.
Check changes i have made in your code.. getIntent() should be called
inside oncreate...
public class SecondActivity extends AppCompatActivity {
ListView lListView;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//changes
Intent intent = getIntent();
ArrayList<String> data =
intent.getExtras().getStringArrayListExtra("dataList");
//changes
lListView = (ListView)findViewById(R.id.lListView);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
lListView.setAdapter(adapter);
}
}
At first set
i.putStringArrayListExtra("dataList",data1);
Then call in Oncreate() section ;
Intent intent = getIntent();
ArrayList<String> data = intent.getStringArrayListExtra("dataList");
Finally
public class SecondActivity extends AppCompatActivity {
ListView lListView;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
ArrayList<String> data = intent.getStringArrayListExtra("dataList");
lListView = (ListView)findViewById(R.id.lListView);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
lListView.setAdapter(adapter);
}
}
You should use i.putStringArrayListExtra("dataList", data1); to set the ArrayList in your code
Try in the other Activity in onCreate():
ArrayList<String> data = (ArrayList<String>) getIntent().getSerializableExtra("dataList");
or
ArrayList<String> data = (ArrayList<String>) getIntent().getParcelableExtra("dataList");

onActivityResult method not working.

I have a small application that launches a "login" activity as a sub activity from my main application activity. The login activity collects username and password using EditText fields and then sends the credentials to main activity for validation after clicking a submit button. For some reason though, my onActivityResult() is not working. I even tried including a TextView that I would manipulate at different points of the method to deduce where it is going wrong, but it appears that the method itself isn't executing for some reason. Any help would be much appreciated.
My MainActivity:
public class MainActivity extends Activity {
private final String userName = "9590778";
private final String userPass = "1234567";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void activity_about(View view){
Intent aboutIntent = new Intent(this, AboutActivity.class);
startActivity(aboutIntent);
}
public void activity_login(View view){
Intent loginIntent = new Intent(this, LoginActivity.class);
startActivityForResult(loginIntent, LoginActivity.LOGIN_REQUEST);
}
public void OnActivityResult(int requestCode, int responseCode, Intent resultIntent){
String passedUser;
String passedPass;
Intent intent = getIntent();
TextView lblTest = (TextView)findViewById(R.id.lblTest);
lblTest.setText("ATLEAST THIS IS WORKING!"); //THIS IS WHERE I AM TRYING TO MANIPULATE THE TEXTVIEW TO SEE IF METHOD IS EXECUTING!
if(requestCode == LoginActivity.LOGIN_REQUEST){
passedUser = intent.getStringExtra("PASSED_USER");
passedPass = intent.getStringExtra("PASSED_PASS");
if(passedUser.equals(userName)){
if(passedPass.equals(userPass)){
lblTest.setText("LOGIN SUCCESSFUL!");
}
}
else{
lblTest.setText("ACCESS DENIED!");
}
}
}
}
Also, this is my LoginActivity:
public class LoginActivity extends Activity {
public static final int LOGIN_REQUEST = 9999;
public static final int LOGIN_RESPONSE = 1234;
private String passedUser;
private String passedPass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login, menu);
return true;
}
public void submitCred(View view){
Intent intent = getIntent();
EditText lblUser = (EditText)findViewById(R.id.txtUserName);
EditText lblPass = (EditText)findViewById(R.id.txtPassword);
passedUser = lblUser.getText().toString();
passedPass = lblPass.getText().toString();
intent.putExtra("PASSED_USER", passedUser);
intent.putExtra("PASSED_PASS", passedPass);
setResult(LOGIN_RESPONSE, intent);
finish();
}
}
You have a typo, the function you want is onActivityResult, (notice the lowercase o).
It's a good habit to use the #Override statement before any method you want to override. If you put #Override before OnActivityResult in your case it would complain at you that OnActivityResult is not a superclass method.
It's a good check to make sure you have the right name and right parameters.

problem with ListActivity

The following is my code for SettingsActivity.java. The main activity starts this activity by calling onScreenSettings(this)
public class SettingsActivity extends ListActivity{
static String[] main_settings = {"mode",
"timeout"
};
static String[] mode = { "Audio",
"Video",
"Audio/Video"
};
static String[] timeout = {
"1 min",
"5 min",
"10 min"
};
static String result;
static String[] display;
boolean settings_selected = false;
static String TAG = "****ALIST****";
public static void onScreenSettings(Activity c){
display = main_settings;
Log.d(TAG,"inside onScreenSettings");
Intent intent = new Intent(c.getApplication(),SettingsActivity.class);
try{
c.startActivityForResult(intent,1);
Log.d(TAG,"after starting activity in onScreenSettings");
}catch(Exception e){
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"inside onCreate-before setting listview");
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, display));
getListView().setTextFilterEnabled(true);
Log.d(TAG,"inside oncreate-after setting listview");
}
public void onListItemClick(ListView l, View v, int position, long id){
result = (String) l.getItemAtPosition(position);
if(!settings_selected){
if(result.equals("mode")){
display = mode;
}
else if(result.equals("timeout")){
display = timeout;
}
settings_selected = true;
Log.d(TAG,"if !setting_selected");
}
else{/*accepting the sub options*/
display = main_settings;//next the main settings must be displayed
if(result.equals("Audio")){
}
else if(result.equals("Video")){
Log.d(AndroidRecorder.TAG,"inside sub option Video");
}
else if(result.equals("Audio/Video")){
}
settings_selected = false;
Log.d(TAG,"if setting_selected");
}
Intent intent = new Intent(this.getApplication(),SettingsActivity.class);
try{
startActivityForResult(intent,1);
Log.d(TAG,"after starting activity in ListItemClick");
}
catch(Exception e){
}
}
public void onActivityResult(int requestCode, int resultCode,Intent data) {
//nothing to do with the intent here
Log.d(TAG,"inside onActivityResult");
setResult(RESULT_OK, data);
finish();
Log.d(TAG,"inside onActivityResult-after finish()");
}
/*public void onBackPressed(){
Log.d(TAG,"inside onBackPressed");
finish();
Log.d(TAG,"inside onBackPressed-after finish()");
}*/
}//end of ListActivity
Problem is control is not entering the else /*accepting the sub options*/ and I can't figure out why. As a result, the mode or timeout list is getting displayed again and again and the main_settings is not displayed.
Please help.
When you call startActivityForResult in onListItemClick you get a whole new instance of the SettingsActivity. Does logcat show "inside oncreate" right after it shows "if !setting_selected"?
If it does and you don't want to go through major refactoring, you can stuff the value of setting_selected into an extra on the intent and pull it out in onCreate.

Categories

Resources