// Данные не передаются другим активам, и переменная объединения не получает значения в OnActivityResult (), поскольку вы говорите мне, как это сделать, потому что мне нужно передать значение объединения в Camera Activity
public class Login extends AppCompatActivity implements OnConnectionFailedListener, View.OnClickListener, ConnectionCallbacks {
GoogleApiClient mGoogleApiClient;
GoogleSignInOptions gso;
SignInButton signIn_btn;
SharedPreferences sharedPreferences;
boolean loggedIn;
private static final int RC_SIGN_IN = 0;
ImageView camerat,galleryt;
String combine;
TelephonyManager tMgr;
String name,email;
// boolean b=true;
ProgressDialog progress_dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// camerat = (ImageView) findViewById(R.id.btn);
//galleryt= (ImageView) findViewById(R.id.btn2);
sharedPreferences = getSharedPreferences("APP", MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean("isLogin", false);
name = sharedPreferences.getString("name", "");
email = sharedPreferences.getString("e_mail", "");
String ID = sharedPreferences.getString("ID", "");
// String mPhoneNumber = tMgr.getLine1Number();
tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
combine = name + "~" + tMgr.getLine1Number() + "~" + email;
System.out.println("sss===" + name + email);
if(loggedIn) {
Intent i = new Intent(Login.this, Camera.class);
System.out.println("chokha " + name + combine);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("combine_data", combine);
// bundle.putString("combine_data2",email);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
finish();
}
else
{
buidNewGoogleApiClient();
customizeSignBtn();
setBtnClickListeners();
progress_dialog = new ProgressDialog(this);
progress_dialog.setMessage("Signing in....");
System.out.println("sss" + name + email);
}
// oncreate ends here
}
/*
Configure sign-in to request the user's ID, email address, and basic profile.
User's ID and basic profile are included in DEFAULT_SIGN_IN.
create and initialize GoogleApiClient object to use Google Sign-In API and the options specified by gso..
*/
private void buidNewGoogleApiClient(){
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this )
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
/*
Customize sign-in button. The sign-in button can be displayed in
multiple sizes and color schemes. It can also be contextually
rendered based on the requested scopes. For example. a red button may
be displayed when Google+ scopes are requested, but a white button
may be displayed when only basic profile is requested. Try adding the
Plus.SCOPE_PLUS_LOGIN scope to see the difference.
*/
private void customizeSignBtn(){
signIn_btn = (SignInButton) findViewById(R.id.sign_in_button);
signIn_btn.setSize(SignInButton.SIZE_STANDARD);
signIn_btn.setScopes(gso.getScopeArray());
}
/*
Set on click Listeners on the sign-in sign-out and disconnect buttons
*/
private void setBtnClickListeners(){
// Button listeners
signIn_btn.setOnClickListener(this);
// findViewById(R.id.sign_out_button).setOnClickListener(this);
// findViewById(R.id.disconnect_button).setOnClickListener(this);
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
Toast.makeText(this, "pita", Toast.LENGTH_SHORT).show();
progress_dialog.dismiss();
Toast.makeText(this, "chita", Toast.LENGTH_SHORT).show();
}
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
getSignInResult(result);
/*System.out.println("Changu "+combine);
GetSet o =new GetSet();
o.setCombine(combine);
Intent intent = new Intent(Login.this, Camera.class);
startActivity(intent);
finish();*/
if (resultCode == RESULT_OK) {
progress_dialog.dismiss();
Toast.makeText(this, "mitra", Toast.LENGTH_SHORT).show();
total();
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
Toast.makeText(this, "start sign process", Toast.LENGTH_SHORT).show();
gSignIn();
break;
/*
case R.id.sign_out_button:
Toast.makeText(this, "Google Sign Out", Toast.LENGTH_SHORT).show();
gSignOut();
break;
case R.id.disconnect_button:
Toast.makeText(this, "Google Access Revoked", Toast.LENGTH_SHORT).show();
gRevokeAccess();
break;*/
/* case R.id.btn:
camerat.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(Login.this, Camera.class);
startActivity(intent);
}
});
break;
case R.id.btn2:
camerat.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Login.this, Camera.class);
startActivity(intent);
}
});
break;*/
}
}
private void gSignIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
Toast.makeText(this, "zombie", Toast.LENGTH_SHORT).show();
progress_dialog.show();
}
private void gSignOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void gRevokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void getSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
String id_token = acct.getIdToken(); //add this code here to save it by use SharedPreferences
// TextView user_name= (TextView)findViewById(R.id.userName);
// TextView email_id= (TextView)findViewById(R.id.emailId);
// user_name.setText("UserName: "+ acct.getDisplayName());
//email_id.setText("Email Id: " + acct.getEmail());
updateUI(true);
SharedPreferences sharedPreferences = getSharedPreferences("APP", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLogin", true);
editor.putString("name", acct.getDisplayName());
editor.putString("e_mail", acct.getEmail());
editor.putString("ID", acct.getIdToken());
editor.commit();
progress_dialog.dismiss();
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
private void updateUI(boolean signedIn) {
if (signedIn) {
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
// findViewById(R.id.btn).setVisibility(View.VISIBLE);
// findViewById(R.id.btn2).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
// findViewById(R.id.btn).setVisibility(View.GONE);
// findViewById(R.id.btn2).setVisibility(View.GONE);
}
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
void total()
{
Intent i = new Intent(Login.this, Camera.class);
System.out.println("chokha " + name + combine);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("combine_data", combine);
// bundle.putString("combine_data2",email);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
finish();
}
}
//Camera.java работает отлично
public class Camera extends AppCompatActivity implements View.OnClickListener {
public static final String UPLOAD_URL = "http://link.com/ImageUpload/upload.php";
public static final String UPLOAD_KEY = "image";
public static final String UPLOAD_KEYS = "name";
public static final String TAG = "MY MESSAGE";
boolean b=false,m;
private int PICK_IMAGE_REQUEST = 1;
String mock;
private Button buttonChoose;
String uploadImage;
private Button buttonUpload,buttonView;
private ImageView imageView;
private Bitmap bitmap,bitmaps;
private Uri filePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonView = (Button) findViewById(R.id.buttonViewImage);
buttonUpload.setEnabled(false);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
buttonView.setOnClickListener(this);
/* GetSet b= new GetSet();
String maths=b.getCombine();
*/
// System.out.println("Matru "+maths);
Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString("combine_data");
// String sss = bundle.getString("combine_data2");
System.out.println("changa " + stuff);
String[] max=stuff.split("~");
for(int i=0;i<max.length;i++)
System.out.println("binku " + max[i]);
}
private void selectImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
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(b) {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
buttonUpload.setEnabled(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
else {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmaps = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(bitmaps);
buttonUpload.setEnabled(true);
mock= getStringImage(bitmaps);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(){
class UploadImage extends AsyncTask<Bitmap,Void,String>{
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Camera.this, "Uploading Image", "Please wait...",true,true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
imageView.setImageDrawable(null);
buttonUpload.setEnabled(false);
}
@Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
if(b)
uploadImage = getStringImage(bitmap);
else
uploadImage = mock;
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
data.put(UPLOAD_KEYS,"data1");
String result = rh.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
}
@Override
public void onClick(View v) {
if (v == buttonChoose) {
b=true;
m=true;
showFileChooser();
}
if(v == buttonUpload){
if(m) {
uploadImage();
m=false;
}
else
{
Toast.makeText(getApplicationContext(), "Take photo or Choose photo first", Toast.LENGTH_SHORT).show();
// buttonUpload.setEnabled(false);
}
}
if(v == buttonView){
b=false;
m=true;
selectImage();
}
}
}
// Где я должен разместить код в Login.java под кодом, чтобы я получил свои значения и передал эти значения другому Activity
Intent i = new Intent(Login.this, Camera.class);
System.out.println("chokha " + name + combine);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("combine_data", combine);
// bundle.putString("combine_data2",email);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
finish();
Я думаю, что метод, который вы должны использовать:
public void startActivityForResult (Intent intent, int requestCode)
Кроме того, вам не нужно вызывать finish () в исходном действии после начала следующего действия.
Вы можете прочитать больше об этом здесь: http://developer.android.com/training/basics/intents/result.html
А как насчет добавления этих данных для намерения? Это тоже не работает?
Что-то вроде:
i.putExtra("name","John");
РЕДАКТИРОВАТЬ
Во втором упражнении вы получите такие данные:
Intent intent = getIntent();
String myName = intent.getStringExtra("name");
// Данные не передаются другим активам, и переменная объединения не получает значения в OnActivityResult (), поскольку вы говорите мне, как это сделать, потому что мне нужно передать значение объединения в Camera Activity
public class Login extends AppCompatActivity implements OnConnectionFailedListener, View.OnClickListener, ConnectionCallbacks {
GoogleApiClient mGoogleApiClient;
GoogleSignInOptions gso;
SignInButton signIn_btn;
SharedPreferences sharedPreferences;
boolean loggedIn;
private static final int RC_SIGN_IN = 0;
ImageView camerat,galleryt;
String combine;
TelephonyManager tMgr;
String name,email;
// boolean b=true;
ProgressDialog progress_dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// camerat = (ImageView) findViewById(R.id.btn);
//galleryt= (ImageView) findViewById(R.id.btn2);
sharedPreferences = getSharedPreferences("APP", MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean("isLogin", false);
name = sharedPreferences.getString("name", "");
email = sharedPreferences.getString("e_mail", "");
String ID = sharedPreferences.getString("ID", "");
// String mPhoneNumber = tMgr.getLine1Number();
tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
combine = name + "~" + tMgr.getLine1Number() + "~" + email;
System.out.println("sss===" + name + email);
if(loggedIn) {
Intent i = new Intent(Login.this, Camera.class);
System.out.println("chokha " + name + combine);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("combine_data", combine);
// bundle.putString("combine_data2",email);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
finish();
}
else
{
buidNewGoogleApiClient();
customizeSignBtn();
setBtnClickListeners();
progress_dialog = new ProgressDialog(this);
progress_dialog.setMessage("Signing in....");
System.out.println("sss" + name + email);
}
// oncreate ends here
}
/*
Configure sign-in to request the user's ID, email address, and basic profile.
User's ID and basic profile are included in DEFAULT_SIGN_IN.
create and initialize GoogleApiClient object to use Google Sign-In API and the options specified by gso..
*/
private void buidNewGoogleApiClient(){
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this )
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
/*
Customize sign-in button. The sign-in button can be displayed in
multiple sizes and color schemes. It can also be contextually
rendered based on the requested scopes. For example. a red button may
be displayed when Google+ scopes are requested, but a white button
may be displayed when only basic profile is requested. Try adding the
Plus.SCOPE_PLUS_LOGIN scope to see the difference.
*/
private void customizeSignBtn(){
signIn_btn = (SignInButton) findViewById(R.id.sign_in_button);
signIn_btn.setSize(SignInButton.SIZE_STANDARD);
signIn_btn.setScopes(gso.getScopeArray());
}
/*
Set on click Listeners on the sign-in sign-out and disconnect buttons
*/
private void setBtnClickListeners(){
// Button listeners
signIn_btn.setOnClickListener(this);
// findViewById(R.id.sign_out_button).setOnClickListener(this);
// findViewById(R.id.disconnect_button).setOnClickListener(this);
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
Toast.makeText(this, "pita", Toast.LENGTH_SHORT).show();
progress_dialog.dismiss();
Toast.makeText(this, "chita", Toast.LENGTH_SHORT).show();
}
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
getSignInResult(result);
/*System.out.println("Changu "+combine);
GetSet o =new GetSet();
o.setCombine(combine);
Intent intent = new Intent(Login.this, Camera.class);
startActivity(intent);
finish();*/
if (resultCode == RESULT_OK) {
progress_dialog.dismiss();
Toast.makeText(this, "mitra", Toast.LENGTH_SHORT).show();
total();
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
Toast.makeText(this, "start sign process", Toast.LENGTH_SHORT).show();
gSignIn();
break;
/*
case R.id.sign_out_button:
Toast.makeText(this, "Google Sign Out", Toast.LENGTH_SHORT).show();
gSignOut();
break;
case R.id.disconnect_button:
Toast.makeText(this, "Google Access Revoked", Toast.LENGTH_SHORT).show();
gRevokeAccess();
break;*/
/* case R.id.btn:
camerat.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent intent = new Intent(Login.this, Camera.class);
startActivity(intent);
}
});
break;
case R.id.btn2:
camerat.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Login.this, Camera.class);
startActivity(intent);
}
});
break;*/
}
}
private void gSignIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
Toast.makeText(this, "zombie", Toast.LENGTH_SHORT).show();
progress_dialog.show();
}
private void gSignOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void gRevokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void getSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
String id_token = acct.getIdToken(); //add this code here to save it by use SharedPreferences
// TextView user_name= (TextView)findViewById(R.id.userName);
// TextView email_id= (TextView)findViewById(R.id.emailId);
// user_name.setText("UserName: "+ acct.getDisplayName());
//email_id.setText("Email Id: " + acct.getEmail());
updateUI(true);
SharedPreferences sharedPreferences = getSharedPreferences("APP", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLogin", true);
editor.putString("name", acct.getDisplayName());
editor.putString("e_mail", acct.getEmail());
editor.putString("ID", acct.getIdToken());
editor.commit();
progress_dialog.dismiss();
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
private void updateUI(boolean signedIn) {
if (signedIn) {
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
// findViewById(R.id.btn).setVisibility(View.VISIBLE);
// findViewById(R.id.btn2).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
// findViewById(R.id.btn).setVisibility(View.GONE);
// findViewById(R.id.btn2).setVisibility(View.GONE);
}
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
void total()
{
Intent i = new Intent(Login.this, Camera.class);
System.out.println("chokha " + name + combine);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("combine_data", combine);
// bundle.putString("combine_data2",email);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
finish();
}
}
//Camera.java работает отлично
public class Camera extends AppCompatActivity implements View.OnClickListener {
public static final String UPLOAD_URL = "http://link.com/ImageUpload/upload.php";
public static final String UPLOAD_KEY = "image";
public static final String UPLOAD_KEYS = "name";
public static final String TAG = "MY MESSAGE";
boolean b=false,m;
private int PICK_IMAGE_REQUEST = 1;
String mock;
private Button buttonChoose;
String uploadImage;
private Button buttonUpload,buttonView;
private ImageView imageView;
private Bitmap bitmap,bitmaps;
private Uri filePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonView = (Button) findViewById(R.id.buttonViewImage);
buttonUpload.setEnabled(false);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
buttonView.setOnClickListener(this);
/* GetSet b= new GetSet();
String maths=b.getCombine();
*/
// System.out.println("Matru "+maths);
Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString("combine_data");
// String sss = bundle.getString("combine_data2");
System.out.println("changa " + stuff);
String[] max=stuff.split("~");
for(int i=0;i<max.length;i++)
System.out.println("binku " + max[i]);
}
private void selectImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
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(b) {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
buttonUpload.setEnabled(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
else {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmaps = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(bitmaps);
buttonUpload.setEnabled(true);
mock= getStringImage(bitmaps);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(){
class UploadImage extends AsyncTask<Bitmap,Void,String>{
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Camera.this, "Uploading Image", "Please wait...",true,true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
imageView.setImageDrawable(null);
buttonUpload.setEnabled(false);
}
@Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
if(b)
uploadImage = getStringImage(bitmap);
else
uploadImage = mock;
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
data.put(UPLOAD_KEYS,"data1");
String result = rh.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
}
@Override
public void onClick(View v) {
if (v == buttonChoose) {
b=true;
m=true;
showFileChooser();
}
if(v == buttonUpload){
if(m) {
uploadImage();
m=false;
}
else
{
Toast.makeText(getApplicationContext(), "Take photo or Choose photo first", Toast.LENGTH_SHORT).show();
// buttonUpload.setEnabled(false);
}
}
if(v == buttonView){
b=false;
m=true;
selectImage();
}
}
}
// Где я должен разместить код в Login.java под кодом, чтобы я получил свои значения и передал эти значения другому Activity
Intent i = new Intent(Login.this, Camera.class);
System.out.println("chokha " + name + combine);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("combine_data", combine);
// bundle.putString("combine_data2",email);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
finish();
Я думаю, что метод, который вы должны использовать:
public void startActivityForResult (Intent intent, int requestCode)
Кроме того, вам не нужно вызывать finish () в исходном действии после начала следующего действия.
Вы можете прочитать больше об этом здесь: http://developer.android.com/training/basics/intents/result.html
А как насчет добавления этих данных для намерения? Это тоже не работает?
Что-то вроде:
i.putExtra("name","John");
РЕДАКТИРОВАТЬ
Во втором упражнении вы получите такие данные:
Intent intent = getIntent();
String myName = intent.getStringExtra("name");