I have app one and app two. In app one I'm sending a string to app two. I want also to return a value from app two to app one. This is my code :
App One:
package ed.letslearn.com.appone;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private static final int SOME_CONSTANT = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle b=new Bundle();
String a="Test";
b.putString("test",a);
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("ed.letslearn.com.apptwo");
launchIntent.putExtras(b);
startActivityForResult(launchIntent, SOME_CONSTANT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (SOME_CONSTANT) : {
if (resultCode == Activity.RESULT_OK) {
String thedata = data.getStringExtra("result");
Log.d("The data",thedata);
}
break;
}
}
}
}
App Two:
package ed.letslearn.com.apptwo;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText thesentvalue=(EditText)findViewById(R.id.editText2);
Button b=(Button)findViewById(R.id.button);
Bundle bundle=getIntent().getExtras();
String text=bundle.getString("test");
thesentvalue.setText(text);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent("ed.letslearn.com.appone");
goBack.putExtra("result", "Sent from App two");
setResult(Activity.RESULT_OK, goBack);
finish();
}
});
}
}
I'm not getting the returned string from app two in app one. Any help please ?
Related
i get some problem when i use the intent, he said "cannot resolve constructor Intent('....')" , i dont know what is wrong in my code but you can see what i m importing here
package com.example.noen.myintentapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn_move);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_move:
Intent intn = new Intent(MainActivity.this,target1.class);
break;
}
}
}
I am developing a chat app using Firebase Realtime Database. I have been able to send and receive messages properly. Now, I want to implement notification whenever new message is received.i.e whenever any user sends a message a push notification triggers at other user device who have that app just like whatsapp.
My main concern is how to do that part in my given below code?
OnlineActivity.java
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.format.DateFormat;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import hani.momanii.supernova_emoji_library.Actions.EmojIconActions;
import hani.momanii.supernova_emoji_library.Helper.EmojiconEditText;
import hani.momanii.supernova_emoji_library.Helper.EmojiconTextView;
import static com.yef.youthempower.youth.R.layout.activity_online;
public class OnlineActivity extends AppCompatActivity {
private static int SIGN_IN_REQUEST_CODE = 1;
private FirebaseListAdapter<ChatMessage> adapter;
RelativeLayout activity_online;
//Add Emojicon
EmojiconEditText emojiconEditText;
ImageView emojiButton,submitButton;
EmojIconActions emojIconActions;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SIGN_IN_REQUEST_CODE)
{
if(resultCode == RESULT_OK)
{
Snackbar.make(activity_online, "Successfully signed
in.Welcome!", Snackbar.LENGTH_SHORT).show();
displayChatMessage();
}
else{
Snackbar.make(activity_online,"We couldn't sign you in.Please
try again later", Snackbar.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_online);
activity_online=(RelativeLayout)findViewById(R.id.activity_online);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
emojiButton = (ImageView)findViewById(R.id.emoji_button);
submitButton = (ImageView)findViewById(R.id.submit_button);
emojiconEditText =
(EmojiconEditText)findViewById(R.id.emojicon_edit_text);
emojIconActions = new
EmojIconActions(getApplicationContext(),
activity_online,emojiButton,emojiconEditText);
emojIconActions.ShowEmojicon();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().push().setValue(new ChatMessage(emojiconEditText.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getEmail()));
emojiconEditText.setText("");
emojiconEditText.requestFocus();
}
});
//Check if not sign-in then navigate Signin page
if(FirebaseAuth.getInstance().getCurrentUser() == null)
{
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(),SIGN_IN_REQUEST_CODE);
}
else
{
Snackbar.make(activity_online,"Welcome "+FirebaseAuth.getInstance().getCurrentUser().getEmail(),Snackbar.LENGTH_SHORT).show();
//Load content
displayChatMessage();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
private void displayChatMessage() {
ListView listOfMessage = (ListView)findViewById(R.id.list_of_message);
adapter = new FirebaseListAdapter<ChatMessage>(this,ChatMessage.class,R.layout.list_items,FirebaseDatabase.getInstance().getReference())
{
#Override
protected void populateView(View v, ChatMessage model, int position) {
//Get references to the views of list_items.xml
TextView messageText, messageUser, messageTime;
messageText = (EmojiconTextView) v.findViewById(R.id.message_text);
messageUser = (TextView) v.findViewById(R.id.message_user);
messageTime = (TextView) v.findViewById(R.id.message_time);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
}
};
listOfMessage.setAdapter(adapter);
}
}
You can easily send notifications from firebase console,
Refer the docs : https://firebase.google.com/docs/cloud-messaging/
https://proandroiddev.com/mastering-firebase-notifications-36a3ffe57c41
But you are asking for sort of automatic notification, this is a bit tricky but you can do this by
Using firebase cloud functions.
Video tutorial : https://www.youtube.com/playlist?list=PLGCjwl1RrtcRHjHyZAxm_Mq4qvtnundo0
By a post request to your firebase server,
Docs : https://firebase.google.com/docs/cloud-messaging/send-message
How to send device to device messages using Firebase Cloud Messaging?
I have a .sql database which I edit using PHPmyadmin and a android app that retrieves the login credentials from the database and tries to login to the app according to the user's credentials. But it keeps showing "Unable to login" error in the app even though I use the correct credentials from the database, which in this case is phoneno and password. The Login_Activity.JAVA is as below. Why is the app not logging in properly?
Login_Activity.java
package com.example.ankit.mrestro.Controller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.squareup.otto.Subscribe;
import com.example.ankit.mrestro.Bus.BusProvider;
import com.example.ankit.mrestro.Bus.LoginEvent;
import com.example.ankit.mrestro.Bus.LoginSuccessEvent;
import com.example.ankit.mrestro.Bus.PushRegisterEvent;
import com.example.ankit.mrestro.R;
import com.example.ankit.mrestro.model.LoginResult;
import com.example.ankit.mrestro.services.DataService;
import com.example.ankit.mrestro.services.RESTrepository;
public class LoginActivity extends Activity {
public static final String PREF_ACCOUNT_ID = "cust_id";
public static final String PREF_TOKEN = "accessToken";
public static final String SHARED_PREF_DB_NAME = "loginResult";
private ProgressDialog progressDialog;
public static Intent createIntent(Context c) {
return new Intent(c, LoginActivity.class);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataService.init();
progressDialog = new ProgressDialog(this);
/**
* Check either we are already logged in
*/
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DB_NAME, 0);
if (sharedPreferences.getString(PREF_TOKEN, "").length() != 0) {
RESTrepository.setToken(sharedPreferences.getString(PREF_TOKEN, ""));
RESTrepository.setUser_id(sharedPreferences.getInt(PREF_ACCOUNT_ID, 0));
goToMainActivity();
}
setContentView(R.layout.activity_login);
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
"hwfeocSIPlgKTasIuARPREnS");
//SharedPreferences preferences=getSharedPreferences("pushService",0);
//String userId=preferences.getString("user_id","no data");
//Toast.makeText(this,"user id is:"+userId,Toast.LENGTH_SHORT).show();
Button loginButton=(Button)findViewById(R.id.email_sign_in_button);
loginButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String phoneno=((TextView)findViewById(R.id.email)).getText().toString();
String password=((TextView)findViewById(R.id.password)).getText().toString();
// Toast.makeText(getBaseContext(),"login..."+phoneno+"..."+password,Toast.LENGTH_SHORT).show();
progressDialog.show();
BusProvider.get().post(new LoginEvent(phoneno,password));
}
});
}
#Override
protected void onResume(){
super.onResume();
BusProvider.get().register(this);
}
#Override
protected void onPause(){
super.onPause();
BusProvider.get().unregister(this);
}
#Subscribe
public void onLoginSuccessEvent(LoginSuccessEvent loginSuccessEvent){
progressDialog.hide();
LoginResult result=loginSuccessEvent.getResult();
if (result != null) {
// Toast.makeText(this,result.getCust_id()+result.getCust_name()+result.getCust_access_token(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,"Login Success",Toast.LENGTH_SHORT).show();
SharedPreferences preferences = this.getSharedPreferences(SHARED_PREF_DB_NAME, MODE_PRIVATE);
preferences.edit().putString(PREF_TOKEN,result.getCust_access_token()).commit();
preferences.edit().putInt(PREF_ACCOUNT_ID,result.getCust_id()).commit();
SharedPreferences pushPreferences=this.getSharedPreferences("pushService",0);
BusProvider.get().post(new PushRegisterEvent
(result.getCust_id(),result.getCust_access_token(),pushPreferences.getString("user_id","")));
goToMainActivity();
} else {
Toast.makeText(this, "Unable to login, please retry", Toast.LENGTH_SHORT).show();
}
}
private void goToMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
I have a shake listener implemented. There are a set of activities (songs) in my code which I want to call when the shake is detected. I tried calling the intent/activity from the onShake method but cannot get them to work. Here is my code...
package com.mellowbluestuff;
import java.util.List;
import com.example.android.searchabledict.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import java.util.List;
import com.mellowbluestuff.*;
import com.mellowbluestuff.ShakeDetector.OnShakeListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;
public class Music extends Activity {
// The following are used for the shake detection
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
mShakeDetector.setOnShakeListener(new OnShakeListener() {
#Override
public void onShake(int count) {
// Create notification if the device is shaken by user
Toast.makeText(getApplicationContext(), "You've shooken the fookin phone", Toast.LENGTH_LONG).show();
// play a random song from the music players below
}
});
}
#Override
public void onResume() {
super.onResume();
// Add the following line to register the Session Manager Listener onResume
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onPause() {
// Add the following line to unregister the Sensor Manager onPause
mSensorManager.unregisterListener(mShakeDetector);
super.onPause();
}
// MUSIC PLAYERS //
// begin MusicPlayerA by calling as an intent
public void MusicPlayer1 (View view) {
Intent m = new Intent (this, MusicPlayerA.class);
startActivity(m);
}
// begin MusicPlayerB by calling as an intent
public void MusicPlayer2 (View view) {
Intent m2 = new Intent (this, MusicPlayerB.class);
startActivity(m2);
}
// begin MusicPlayerC by calling as an intent
public void MusicPlayer3 (View view) {
Intent m3 = new Intent (this, MusicPlayerC.class);
startActivity(m3);
}
// begin MusicPlayerD by calling as an intent
public void MusicPlayer4 (View view) {
Intent m4 = new Intent (this, MusicPlayerD.class);
startActivity(m4);
}
// begin MusicPlayerE by calling as an intent
public void MusicPlayer5 (View view) {
Intent m5 = new Intent (this, MusicPlayerE.class);
startActivity(m5);
}
// begin MusicPlayerF by calling as an intent
public void MusicPlayer6 (View view) {
Intent m6 = new Intent (this, MusicPlayerF.class);
startActivity(m6);
}
// begin MusicPlayerG by calling as an intent
public void MusicPlayer7 (View view) {
Intent m7 = new Intent (this, MusicPlayerG.class);
startActivity(m7);
}
// begin MusicPlayerH by calling as an intent
public void MusicPlayer8 (View view) {
Intent m8 = new Intent (this, MusicPlayerH.class);
startActivity(m8);
}
//handler for back button
public void BackButton (View view) {
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent s = new Intent (this, Main.class);
startActivity(s);
}
#Override
public void onBackPressed() {
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent btm = new Intent (this, Main.class);
startActivity(btm);
};
}
I got an application where you can make and save a picture. Now I when this picture to display in another class. I just started programming in java and have no idea how to do this.
FotoMaker.java:
package com.example.random;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.net.Uri;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class FotoMaker extends Activity
{
ImageView iv;
Uri uriOfPicture;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addpictolist);
iv = (ImageView) findViewById(R.id.imageView);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick (View v){
takeImageFromCamera();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == 0)
{
Bitmap image=createBitmapFromURI(uriOfPicture);
iv.setImageBitmap(image);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (uriOfPicture != null) {
outState.putString("cameraImageUri", uriOfPicture.toString());
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
uriOfPicture = Uri.parse(savedInstanceState.getString("cameraImageUri"));
}
}
public void takeImageFromCamera(){
String fileName = "new-photo-name.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image captured by camera");
uriOfPicture = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Log.i("uri",uriOfPicture.toString());
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriOfPicture);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent,
0);
}
public Bitmap createBitmapFromURI(Uri uri) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getApplicationContext()
.getContentResolver().openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (bitmap != null)
return Bitmap.createScaledBitmap(bitmap, 100, 100, true);
else {
return null;
}
}
}
ShowPhoto.java:
package com.example.random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class ShowPhoto extends Activity{
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.watch_pic);
iv = (ImageView) findViewById(R.id.imageView1);
}
}
You can pass the URI to the new activity once you have it. So, in your FotoMaker's onActivityResult just start the ShowPhoto activity and send the uriOfPicture in an extra.
Intent intent = new Intent(this, ShowPhoto.class);
intent.putExtra("uri", uriOfPicture);
startActivity(intent);
In your ShowPhoto activity just catch the argument and show it:
String uriOfPicture = getIntent().getStringExtra("uri");
Bitmap image = createBitmapFromURI(uriOfPicture);
iv.setImageBitmap(image);
I'm assuming most of your code already works.