Android Studio Value isn't passed over to other activity - java

I have a problem. I got a simple clicker here, but the "upgraded clicks per tap" are not transferred to the other activity. I don't know why it is not working.
Code as below :
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE_CURRENTCLICKS = 10;
public int amountClicks = 0;
public int incrementAmount = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnClick = (Button) findViewById(R.id.btnClick);
final TextView tvAmountClicks = (TextView) findViewById(R.id.tvAmoutClicks);
Button btnShop = (Button) findViewById(R.id.btnShop);
amountClicks = getIntent().getIntExtra("currentClicks", 0);
incrementAmount = getIntent().getIntExtra("upgradedClicks", 1);
tvAmountClicks.setText(""+amountClicks);
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
amountClicks += incrementAmount;
tvAmountClicks.setText(""+amountClicks);
}
});
btnShop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ShopActivity.class);
intent.putExtra("currentClicks",amountClicks);
startActivityForResult(intent, REQUEST_CODE_CURRENTCLICKS);
}
});
}
}
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ShopActivity extends AppCompatActivity {
public int currentClicks;
public int incrementAmount;
public int upgradedClicks;
public int upgradeCost = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
currentClicks = getIntent().getIntExtra("currentClicks",0);
final TextView tvCurrentClicks = (TextView) findViewById(R.id.tvCurrentClicks);
tvCurrentClicks.setText(""+currentClicks);
Button btnUpgrade = (Button) findViewById(R.id.btnUpgrade);
btnUpgrade.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(upgradeCost > currentClicks)
{
Context context = getApplicationContext();
CharSequence text = "You don't have enough Clicks";
int duration = Toast.LENGTH_SHORT;
Toast cantUpgrade = Toast.makeText(context, text,duration);
cantUpgrade.show();
}
else
{
currentClicks -= upgradeCost;
upgradedClicks++;
tvCurrentClicks.setText(""+ currentClicks);
}
Intent intent = new Intent();
intent.putExtra("currentClicks",currentClicks);
intent.putExtra("upgradedClicks",upgradedClicks);
setResult(RESULT_OK, intent);
}
});
}
}

If I return back to the main activity, it doesnt return the "upgraded clicks" nor the "current clicks".
You have startActivityForResult therefore you need to implement onActivityResult
So, you have this code
Intent intent = new Intent();
intent.putExtra("currentClicks",currentClicks);
intent.putExtra("upgradedClicks",upgradedClicks);
setResult(RESULT_OK, intent);
finish(); // Add finish() to end this Activity
And that would go back to the calling Activity where you check the request code.
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE_CURRENTCLICKS = 10;
public int amountClicks = 0;
private TextView tvAmountClicks;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_CODE_CURRENTCLICKS) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
amountClicks = data.getIntExtra("currentClicks", 0);
int upgradedClicks = data.getIntExtra("upgradedClicks", 1);
tvAmountClicks.setText(""+amountClicks);
}
}
}
Android | Getting the result of an Activity

You should override the MainActivity's onResume() method to refresh your data.
EDIT try this one
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
amountClicks = getIntent().getIntExtra("currentClicks", 0);
incrementAmount = getIntent().getIntExtra("upgradedClicks", 1);
tvAmountClicks.setText(""+amountClicks);
}
}
}

Related

Bitmap image choose from gallery not showing in imageview for android version 5.0.2

I found that my function of the app is not working for certain android phone.
I think maybe is the problem of android version? My app is working fine on an other Android phone, so how can I solve this issue?
public class StartActivity extends AppCompatActivity {
private Button btnupload,btnchoose;
private ImageView imgprofile;
Uri filepath;
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
btnchoose = (Button)findViewById(R.id.btn_addphoto);
btnupload = (Button)findViewById(R.id.btn_upload);
imgprofile = (ImageView)findViewById(R.id.imageView);
btnchoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseimage();
}
});
btnupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
private void chooseimage() {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
filepath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filepath);
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
Toast.makeText(StartActivity.this, "YES!", Toast.LENGTH_SHORT).show();
bitmap = Bitmap.createScaledBitmap(bitmap, imgprofile.getWidth(),imgprofile.getHeight(),true);
imgprofile.setImageBitmap(bitmap);
} else {
Toast.makeText(StartActivity.this, "YES!!!!", Toast.LENGTH_SHORT).show();
imgprofile.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I run my app on the phone which is version 5.0.2 it does not show any response of toast.
This is the code works for me. I just change the position of the function, the code still the same.
package com.example.user8.letseat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
import java.util.UUID;
public class StartActivity extends AppCompatActivity {
private Button btnupload,btnchoose;
private ImageView imgprofile;
Uri filepath;
private static final int PICK_IMAGE_REQUEST = 1;
FirebaseStorage firebaseStorage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
btnchoose = (Button)findViewById(R.id.btn_addphoto);
btnupload = (Button)findViewById(R.id.btn_upload);
imgprofile = (ImageView)findViewById(R.id.imageView);
btnchoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
}
});
btnupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadimage();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)
{
filepath = data.getData();
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filepath);
imgprofile.setImageBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadimage() {
if (filepath != null)
{
final ProgressDialog pg = new ProgressDialog(this);
pg.setTitle("Uploading...");
pg.show();
StorageReference ref = storageReference.child("image/" + UUID.randomUUID().toString());
ref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pg.dismiss();
DatabaseReference databaseReference ;
databaseReference= FirebaseDatabase.getInstance().getReference("Imageeee");
String ImageUploadId = databaseReference.push().getKey();
String imageurl = taskSnapshot.getDownloadUrl().toString();
// Adding image upload id s child element into databaseReference.
databaseReference.child(ImageUploadId).setValue(imageurl);
Toast.makeText(StartActivity.this, "FINISH", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pg.dismiss();
Toast.makeText(StartActivity.this, "FAIL"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
pg.setMessage("Uploaded" + (int)progress+"%");
}
});
}
}
}
MyActivity.xml
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:layout_x="13dp"
android:layout_y="112dp" />
MainActivity.java
public class MainActivityextends Activity {
Button imageUpload;
ImageView imageView;
static final int PICTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
imageUpload= (Button) findViewById(R.id.buttonImage);
imageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,PICTURE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==PICTURE && resultCode==RESULT_OK && null !=data)
{
Uri uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor=getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(prjection[0]);
String path=cursor.getString(columnIndex);
cursor.close();
Bitmap selectFile = BitmapFactory.decodeFile(path);
Drawable d = new BitmapDrawable(selectFile);
imageView.setBackground(d);
// imageView.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
Check Simple code of get image from gallery and display hopr this may help you.
Example

Open/Launch Various Apps via Voice Commands using STT

I am trying to create an Android App that can listen to various commands and respond to it accordingly. for e.g, if i press mic and say "open whatsapp", it does it.
Question is How do i open Various apps with limited coding?
following code is to open whatsapp, but if i had to open other various app, Do i need to write same IF Statement for various apps?? wont it be too lenghty?
please provide a better solution.
package example.bot;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends Activity {
private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
* */
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (result.size() == 0) {
} else {
String mostLikelyThingHeard = result.get(0);
// toUpperCase() used to make string comparison equal
if (mostLikelyThingHeard.toUpperCase().equals("OPEN WHATSAPP")) {
//informationMenu();
txtSpeechInput.setText(result.get(0));
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.whatsapp");
//if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
} //else if()
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
//private void informationMenu() {
// Intent intent = new Intent(this, open_app.class);
// startActivity(intent);
//}
#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;
}
}

Android studio use same integer in 2 activities

i was making an android app and i need to use one integer value in 2 activities. I tried using this code but it didn't work.
//Integer Sender
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("MyIntNameGoesHere", intValue);
startActivity(myIntent);
//Integer receiver
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
It says Cannot resolve symbol intValue and Cannot resolve symbol A and the same for B.
Here's the whole code.
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int balance;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Click counter
final TextView text = (TextView) findViewById(R.id.balance_text);
assert text != null;
// to retreuve the values from the shared preference
preferences = PreferenceManager.getDefaultSharedPreferences(this);
balance = preferences.getInt("balance", 0);
text.setText(balance + " $");
final ImageButton button = (ImageButton) findViewById(R.id.click_button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
balance++;
text.setText("" + balance + " $");
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("balance", balance);
editor.apply();
}
});
final Button UpgradesButton = (Button) findViewById(R.id.upgrades_button);
assert UpgradesButton != null;
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, UpgradesActivity.class));
}
});
//Balance Integer Sender
}
}
UpgradesActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
Error code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Receive balance from MainActivity
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(balance >= 300){ //ERROR ON THIS LINE
}
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
ALL ABOVE IS ANSWERED! ---------------------------------------------------------
Now i have problems with this part of the code:
#Override
public void onClick(View v) {
if(balance >= 300){
balance -= 300;
}
if(balance < 300){
final TextView text = (TextView) findViewById(R.id.not_enough_money_text);
assert text != null;
text.setText("You do not have enough money.");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
text.setText("");
}
}, 2000);
}
}
When i click the button it says i do not have enough money but i have over 300. Please help me.
I found out what the problem was but I'm not sure how to fix it. I need to send balance back to MainActivity. Can anyone help with that?
Send the data like this -
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UpgradesActivity.class);
intent.putExtra("key_int", balance);
startActivity(intent);
}
});
And fetch it in onCreate() of UpgradesActivity -
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
You're using different key when sending and receiving the Int.
Change this line:
int intValue = mIntent.getIntExtra("intVariableName", 0);
To this:
int intValue = mIntent.getIntExtra("MyIntNameGoesHere", 0);

Returning a class from StartActivityForResult in Android

I started a activity to grab contacts from a list of all the contacts on the phone. Now my issue is how do I return the selected checks correctly from the listview, directly into my Person class. Im not fully understanding the concept of Intents and Activities in general so please bear with me.
Here is how I start the Activity from MainActivity.java
static final int PICK_CONTACT_REQUEST = 1;
public void grabthecontacts(View view) {
Intent intent = new Intent(getApplicationContext(), SelectContactsActivity.class);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
}
}
}
Here is the class it calls, Select Contacts Activity
package com.example.android.smsapp;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.app.Activity;
import android.provider.ContactsContract;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class SelectContactsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_contacts);
populateListView();
Button SubmitButton = (Button) findViewById(R.id.submitbut);
SubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
registerDoneClick(view);
}
});
}
ArrayList<Person> list = new ArrayList<>();
Set<Person> checkedlist = new HashSet<>();
public void populateListView() {
try {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Person allcontacts = new Person(name, phoneNumber);
list.add(allcontacts);
}
phones.close();
}
catch (Exception e){
e.printStackTrace();
}
ListView listview2 = (ListView) findViewById(R.id.contactlistview);
ArrayAdapter<Person> adapter = new myListAdapter();
listview2.setAdapter(adapter);
listview2.setItemsCanFocus(false);
listview2.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
public class myListAdapter extends ArrayAdapter<Person> {
public myListAdapter() {
super(SelectContactsActivity.this, R.layout.da_item, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.da_item, parent, false);
}
// Find person wot work with
Person currentperson = list.get(position);
// Fill the view
TextView nameboxview = (TextView) itemView.findViewById(R.id.NameView);
nameboxview.setText(currentperson.getName());
TextView numberboxview = (TextView) itemView.findViewById(R.id.NumberView);
numberboxview.setText(currentperson.getPhone());
CheckBox cb = (CheckBox)itemView.findViewById(R.id.checkBox);
cb.setTag(position);
if (cb.isChecked()) {
currentperson.setChecked(true);
}
return itemView;
}
}
public void registerDoneClick(View view) {
for (Person allcontacts : list) {
if(allcontacts.isChecked()) {
Person human = new Person(allcontacts.getName(), allcontacts.getPhone());
}
}
// How do I return human with this activity? or is there another method?
finish();
}
}
Im completely lost on how to return the values I want as a person, so I can simply do
hashsetname.add(human)
Any help even with general formatting is greatly appreciated, or any java tips too. Thank you
Try this,
First make Person class to Serializable,using
public class Person implements Serializable
now set ivalue in intent like this,
Intent returnIntent = new Intent();
returnIntent.putExtra("result", human);
setResult(Activity.RESULT_OK, returnIntent);
finish();
get value from intent in onActivityResult method,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
Person myObject = (Person) data.getParcelableExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
}
}
}
Intent i= new Intent();
i.putExtra("whatever",yourResult);
setResult(Activity.RESULT_OK, i);
finish();
add these two lines before calling finish();
Intent returnIntent = new Intent();
setResult(Activity.RESULT_OK, returnIntent);
finish();

Switching activities/passing data between activities

So using suggestions from the last question I asked, I figured out how to call BarCodeScanner, and return the value to a field. so now, I have a toast that says "successful scan" and then I want to pass the result to a new activity. when I comment out my intent, everything works (minus the passing of data/switching of screen, obviously) but when I run my project as is, it FC's... no errors reported by eclipse in code or XML. Any insights?
package com.mhe.test.scan;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button myScanButton = (Button) findViewById(R.id.myScanButton);
totalbox = (EditText) findViewById(R.id.tBox);
myScanButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
}
});
}
private EditText totalbox;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
final String contents = intent.getStringExtra("SCAN_RESULT");
if ( totalbox != null )
totalbox.setText(contents);
Context context = getApplicationContext();
CharSequence text = "Successful Scan";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent i = new Intent(main.this, Result.class);
i.putExtra("SNARP", "SCAN_RESULT");
startActivityForResult(i, 0);
} else if (resultCode == RESULT_CANCELED) {
if ( totalbox != null )
totalbox.setText("bummer");
}
}
}
}
And then to handle the data being passed, in the new activity:
package com.mhe.test.scan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Result extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Intent i = getIntent();
Bundle b = i.getExtras();
String foosh = b.getString("SNARP");
EditText box1 = (EditText) findViewById(R.id.tBox1);
box1.setText(foosh);
Try sending a Bundle object when calling the new intent.
Intent i = new Intent(main.this, Result.class);
Bundle b = new Bundle();
b.putString("SNARP", "SCAN_RESULT")
i.putExtras(b);
Try getting string in the child Activity this way.
public class Result extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Intent i = getIntent();
String foosh = i.getStringExtra("SNARP");

Categories

Resources