Android intent.getStringExtra() return null - android

MainActivity
public class MainActivity extends AppCompatActivity {
private static final int REQ_CODE_TO_ADD = 123;
final ArrayList<Contact> allContact = new ArrayList();
ArrayList<String> name = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent intent = new Intent(this,DetailActivity.class);
Button addbt = (Button)findViewById(R.id.addbt);
public void onClickAdd(View v){
Intent intent = new Intent(this,AddContactActivity.class);
startActivityForResult(intent,REQ_CODE_TO_ADD);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_CODE_TO_ADD){
if(resultCode == 0){
Intent intent = getIntent();
String name2 = intent.getStringExtra("namev");
String email2 = intent.getStringExtra("emailv");
String birthday2 = intent.getStringExtra("birthdayv");
Log.d("AAA",">>>:"+name2);
Contact person = new Contact(name2,email2,birthday2);
allContact.add(person);
}}
}
}
AddContactActivity
public class AddContactActivity extends AppCompatActivity {
private static final int REQ_CODE_TO_MAIN = 321;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
}
public void onClickOk(View v){
EditText name = (EditText)findViewById(R.id.nameet);
EditText email = (EditText)findViewById(R.id.email);
EditText birthdate = (EditText)findViewById(R.id.birthdate);
Intent intent = new Intent();
intent.putExtra("namev",name.getText().toString());
intent.putExtra("emailv",email.getText().toString());
intent.putExtra("birthdayv",birthdate.getText().toString());
setResult(0,intent);
finish();
}
}
AddContactActivity I already use intent.putExtra name.getText().toString() and send intent to MainActivity
Why onActivityResult() in MainActivity Log.d output is null?

if(resultCode == 0){
//Intent intent = getIntent();
String name2 = data.getStringExtra("namev");
String email2 = data.getStringExtra("emailv");
String birthday2 = data.getStringExtra("birthdayv");
Log.d("AAA",">>>:"+name2);
Contact person = new Contact(name2,email2,birthday2);
allContact.add(person);
}}
you need to use the data not getIntent()

You are using the Intent which originally launched the Activity. Use the Intent which was sent as a parameter instead.

There's no need for
Intent intent = getIntent();
Intent is already passed as argument i.e 'data'
Use this variable to extract data.
Hope this helps.

Intent intent = getIntent(); // This line is wrong
String name2 = intent.getStringExtra("namev");
String email2 = intent.getStringExtra("emailv");
String birthday2 = intent.getStringExtra("birthdayv");
Modify your code like this
if(requestCode==2 && resultCode==RESULT_OK){
Bundle bundle=data.getExtras();// here "data" is your intent
String string=bundle.getString("message");
Log.i(TAG,"onActivityResult Called..."+string);
}

Related

Select Address from MapActivity and return back to MainActivity

I recently started Android Development, I wanted to create a form by which I also take user address. In the address field I placed a button to choose their location by using map, I successfully get location but the problem is when I return back to main activity all my fields become empty such as name,phone,email e.t.c.
I want that all my fields remain filled after selecting map location
Here is my Main Activity
public class MainActivity extends AppCompatActivity {
private EditText Name, Phone, Destination;
private Button mBtnAdd;
private String type = "1";
TextView textView;
LocationManager locationManager;
String lattitude,longitude;
private static final int REQUEST_LOCATION = 1;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = (EditText) findViewById(R.id.name);
Phone = (EditText) findViewById(R.id.phone);
Destination = (EditText) findViewById(R.id.destinationAddress);
Intent i = getIntent();
String address = i.getStringExtra ( "address");
Destination.setText(address);
}
private void pickup() {
Intent intent = new Intent(MainActivity.this, MapsActivity.class);
intent.putExtra ( "map_type", "1" );
startActivity(intent);
}
}
Here Is my select location Function in main Map Activity
public void updateLocation(View view) throws IOException {
final EditText location = (EditText) findViewById(R.id.name);
LatLng center = mMap.getCameraPosition().target;
Log.e(TAG, "Center: " + center);
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(center.latitude, center.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
Log.e(TAG, "addresses: " + addresses);
String address = addresses.get(0).getAddressLine(0);
Intent i = getIntent();
Intent intent = new Intent( MapsActivity.this, MainActivity.class );
intent.putExtra ( "address", address );
startActivity(intent);
}
you need to implement methods onSaveInstanceState and onRestoreInstanceState in your MainActivity:
#Override
protected void onSaveInstanceState(Bundle state) {
/* putting the current instance state into a Bundle */
state.putString(InstanceStateKeys.CURRENT_NAME, this.Name.getText());
state.putString(InstanceStateKeys.CURRENT_PHONE, this.Phone.getText());
state.putString(InstanceStateKeys.CURRENT_DEST, this.Destination.getText());
super.onSaveInstanceState(state);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
/* and then obtain these values from the Bundle again */
String currentName = state.getString(InstanceStateKeys.CURRENT_NAME);
String currentPhone = state.getString(InstanceStateKeys.CURRENT_PHONE);
String currentDest = state.getString(InstanceStateKeys.CURRENT_DEST);
/* in order to update the GUI with these values */
if(currentName != null) {this.Name.setText(currentName);}
if(currentPhone != null) {this.Phone.setText(currentPhone);}
if(currentDest != null) {this.Destination.setText(currentDest);}
}
where InstanceStateKeys is just a class with some String constants, for example:
public class InstanceStateKeys {
public static final String CURRENT_NAME = "name";
public static final String CURRENT_PHONE = "phone";
public static final String CURRENT_DEST = "dest";
}
while actually, you should better use .startActivityForResult() to start that MapsActivity and then handle the result within the MainActivity's implementation of .onActivityResult() ...eg. in order to pass back the destination address.
put together it might look alike this ...
/** start the {#link MapsActivity} for a result: */
private void startMapsActivity() {
Intent intent = new Intent(this.getContext(), MapsActivity.class);
intent.putExtra ("map_type", 1);
this.startActivityForResult(intent, RequestCodes.REQUESTCODE_PICK_DESTINATION);
}
then, in order to return that result to the MainActivity:
public void updateLocation(View view) throws IOException {
...
Intent result = new Intent();
result.putExtra ("address", address);
this.setResult(Activity.RESULT_OK, result);
this.finishActivity(RequestCodes.REQUESTCODE_PICK_DESTINATION);
}
finally, when having returned to the MainActivity:
/** handle the result: */
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
String address = null;
if(resultCode == Activity.RESULT_OK && result != null) {
extras = result.getExtras();
if(extras != null) {
address = extras.getString("address", null);
Log.d(LOG_TAG, "the received address is: " + address);
}
}
}
the SDK documentation explains it pretty well: Understand the Activity Lifecycle.

How do i set .equals equal to the result of startActivityForResult

im kinda new to programming and would like to make some sort of like a login and register page. so from my login page i click register and it would go to the register page and i want the username/password i get from the register page to be used in the previous login page to login into the app. But i cant seem to set the username/password using the result. Only able to set the textview. pls help heres the code
public class MainActivity extends AppCompatActivity {
private EditText Name;
private EditText Password;
private TextView Info;
private Button Login;
private int counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = (EditText)findViewById(R.id.etName);
Password = (EditText)findViewById(R.id.etPass);
Info = (TextView) findViewById(R.id.tvInfo);
Login = (Button)findViewById(R.id.btnLogin);
Info.setText("No Of Attempts Remaining: 5");
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validate(Name.getText().toString(),Password.getText().toString());
}
});
}
private void validate(String userName, String userPassword){
if(userName.equals("") && userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
else{
counter--;
Info.setText("No Of Attempts Remaining: " + String.valueOf(counter));
if(counter == 0){
Login.setEnabled(false);
}
}
}
public void facebooklogin(View myview){
Intent intent = new Intent(this, MenuActivity.class);
startActivity(intent);
}
public void register(View myview) {
Intent i = new Intent(this, RegisterActivity .class);
startActivityForResult(i, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String reginame = data.getStringExtra("NAME");
String regipass = data.getStringExtra("PASS");
Name.setText("" + reginame);
Password.setText("" + regipass);
}
}
}
How do i set the
private void validate(String userName, String userPassword){
if(userName.equals("") && userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
to be equal to the onActivityResult reginame and regipass
your condition is wrong it should be like this:-
private void validate(String userName, String userPassword){
if(!userName.equals("") && !userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
First Activity.
Send information
Intent send = new Intent(MainActivity.this, Main2Activity.class);
send.putExtra("login",editText.getText());
send.putExtra("password",editText1.getText());
startActivity(send);
Second Activity.
Get Information
if(getIntent()!=null){
Intent intent = getIntent();
editText.setText(intent.getStringExtra("login")) ;
editText1.setText(intent.getStringExtra("password")) ;
}

How to go to next activity after sending email in Android by clicking one button?

After sending email, I need to go other activity. But I'm going to next activity before sending email. the same question having answer that tells to use startactivityforresult.bt I'm new to Android. I don't know how to use that.
public class GetQuoteact extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private ProgressDialog loadDialog;
Button btsub;
private String mobilee, namee, emailide, statee, citye, pine, subjecte, streete, success,endresp;
EditText name_c, mobile_c, emailid_c, state_c, city_c, street_c, pin_c, subject_c;
public String batter_feat_id,Modelname,Batterytype = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getquote2);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
name_c = (EditText) findViewById(R.id.name);
mobile_c = (EditText) findViewById(R.id.mobile);
emailid_c = (EditText) findViewById(R.id.email_id);
state_c = (EditText) findViewById(R.id.state);
city_c = (EditText) findViewById(R.id.city);
street_c = (EditText) findViewById(R.id.street);
pin_c = (EditText) findViewById(R.id.pincode);
subject_c = (EditText) findViewById(R.id.subject);
btsub = (Button) findViewById(R.id.bt_sub);
Intent in1 = getIntent();
batter_feat_id = in1.getStringExtra("battery_featuer_idc");
Modelname = in1.getStringExtra("Model_name");
Batterytype = in1.getStringExtra("Battery_type");
btsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inilize();
try {
if (!validate()) {
Toast.makeText(GetQuoteact.this, "Enter necessary details!!!", Toast.LENGTH_SHORT).show();
} else {
showDialog();
onfetch(batter_feat_id);}
} catch (Exception e) {
Toast.makeText(GetQuoteact.this, "" + e, Toast.LENGTH_SHORT).show();
}
}
});
}
public void inilize() {
namee = name_c.getText().toString();
mobilee = mobile_c.getText().toString();
emailide = emailid_c.getText().toString();
statee = state_c.getText().toString();
citye = city_c.getText().toString();
pine = pin_c.getText().toString();
subjecte = subject_c.getText().toString();
streete = street_c.getText().toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Intent intent=new Intent(getApplicationContext(),Lastpage.class);
startActivity(intent);
}
else{
Toast.makeText(GetQuoteact.this, "error on sending mail...", Toast.LENGTH_SHORT).show();
}
}
private void onfetch(String batter_feat_id) {
Intent ithh =new Intent(Intent.ACTION_SENDTO);
ithh.setData(Uri.parse("mailto:"));
String[] to={"abc#gmail.com"};
ithh.putExtra(ithh.EXTRA_EMAIL,to);
ithh.putExtra(ithh.EXTRA_SUBJECT,"Email From JC APP");
ithh.putExtra(ithh.EXTRA_TEXT,"Model Name :"+Modelname
+"\nBattery Type:"+Batterytype
+"\nName :"+namee
+"\nContact no :"+mobilee
+"\nmailid="+emailide
+"\nstate="+statee
+"\ncity="+citye
+"\narea="+streete
+"\npincode="+pine
+"\nsubject="+subjecte);
startActivityForResult(ithh.createChooser(ithh,"Sent!!!"),1);
}
else{
Toast.makeText(GetQuoteact.this, "error!!! ", Toast.LENGTH_SHORT).show();
}
}
}
change your onActivityResult to something like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//autocompleteFragment.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// success open your activity
}
}
}
I hope this helps

How to call a WCF service in an Android Application?

So I have been tasked to create an android application that scans a QR code of a WCF Service URL, then call that URL with a username attached as a query string. I have managed to scan the barcode and create the query string which returns a string list of other URLs as it should when used in a browser but I have no idea how to go through with getting that string list inside of android. The code for getting the query string URL is here:
public class MainActivity extends AppCompatActivity {
private EditText inputUsernameField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputUsernameField = (EditText) findViewById(R.id.inputUsernameField);
}
public void scanNowButtonClick(View view) {
new IntentIntegrator(this).initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String contents = intent.getStringExtra("SCAN_RESULT");
String username = String.valueOf(inputUsernameField.getText());
Uri.Builder b = Uri.parse(contents).buildUpon();
if (username != null) {
b.appendQueryParameter("username", username);
}else{
Toast.makeText(this, "Please input a Username and try again.", Toast.LENGTH_LONG).show();
}
String myUrl = b.build().toString();
Intent myIntent = new Intent(MainActivity.this, ImageActivity.class);
myIntent.putExtra("myUrl", myUrl); //Optional parameters
MainActivity.this.startActivity(myIntent);
}
}
}
The Query URL is http://cmsnet.cms.net.nz/imageservice/persehtmlservice.svc/getimages?site=pukekohe&username=test
The application then starts another activity where the string list of image URLs that should be returned by the WCF call will be shown.
Thanks

Android OnActivityResult passing data to another form and getting array result from it

I want to send some Data to another activity say SecondActivity and then getting Array data from That SecondActivity to Main activity using OnActivityResult
This is a app like when i press upload button i already have path i want to send that path to another activity and then getting the result in array from another activity to same mainactivity and then want to view that array in textview
CSVUpload
public class CSVUploader extends Activity {
Button btnUpload;
EditText txtName;
EditText txtMessageName;
Bundle extras = getIntent().getExtras();
String FullPath = extras.getString("FullPath");
#Override
protected void onCreate(Bundle savedInstanceState) {
try{
File csvfile = new File(FullPath);
FileInputStream csvStream = new FileInputStream(csvfile);
BufferedReader in = new BufferedReader(new InputStreamReader(csvStream));
String line;
String[] name = null;
String[] number = null;
int iCount=0;
while ((line = in.readLine()) != null){
String[] RowData = line.split(",");
name[iCount] = RowData[0];
number[iCount] = RowData[1];
iCount++;
/* ContentValues values = new ContentValues();
values.put(key, value);
values.put(CsvProvider.NUMBER, number);
values.put("status",status);
getContentResolver().insert(CsvProvider.CONTENT_URI, values);
*/ }
in.close();
Bundle b =new Bundle();
Intent intent = new Intent();
b.putStringArray("name", name);
b.putStringArray("number", number);
intent.putExtras(b);
setResult(RESULT_OK, intent);
finish();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
FirstActivity
public void uploadfile(View view){
edittext = (EditText)findViewById(R.id.txtFile);
Toast.makeText(NewMessage.this, FullPath, 2000).show();
if(FullPath != null)
{
Intent intent1 = new Intent(this, CSVUploader.class);
intent1.putExtra("FullPath", FullPath);
startActivityForResult(intent1, 2);
}
else
{
Toast.makeText(NewMessage.this, "No File Selected", 2000).show();
}
}
// Listen for results.
public void onActivityResult(int requestCode, int resultCode, Intent data){
// See which child activity is calling us back.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_PATH){
if (resultCode == RESULT_OK) {
curPathName = data.getStringExtra("GetPath");
curFileName = data.getStringExtra("GetFileName");
FullPath = curPathName+"/"+curFileName;
edittext.setText(curFileName);
/* Toast.makeText(NewMessage.this, resId, duration);*/
}
}
if (requestCode==2){
if (resultCode == RESULT_OK) {
Bundle b=this.getIntent().getExtras();
String[] name=b.getStringArray("name");
String[] number=b.getStringArray("number");
String[] status;
}
}
try to use this code. I am not sure this will work properly
MainActivity.java
public void uploadfile(View view){
Intent intent1 = new Intent(this, CSVUploader.class);
intent1.putExtra("FullPath", FullPath);
startActivity(intent1);
}
Replace your code likewise
CSVUploader.java
Bundle b=new Bundle();
Intent i = new Intent(this,MainActivity.class);
b.putStringArray("name",name);
b.putStringArray("number",number)
i.putExtras(b);
startActivity(i);
You can retrive it in MainActivity.java as
Bundle b=this.getIntent().getExtras();
String[] name=b.getStringArray("name");
String[] number=b.getStringArray("number");
You need to put the retrieving code into onCreate instead of where you have it now.
#Override
protected void onCreate(Bundle savedInstanceState) {
String FullPath = getIntent().getStringExtra("FullPath");
By the way why you want to use another activity to do the task. Why dont you do it in the same activity.

Categories

Resources