What I am doing is sending Intent to MainActivity from Listview the listview item I am displaying in alertbox.
holder.txtStore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String value = holder.txtStore.getText().toString();
Intent myIntent = new Intent(view.getContext(),MainActivity.class);
myIntent.putExtra("restaurant_name", value);
try {
context.startActivity(myIntent);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
Toast.makeText(context, "yourActivity is not founded", Toast.LENGTH_SHORT).show();
}
}
});
In MainActivity right now I am using button to start getIntent but I don't want to use button I just want to start getIntent function when alertbox disappear or ya when MainActivity start I try to use onResume or onRestart. But not work for me.
This is my code to call getIntent using button:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
String restaurant_name = intent.getStringExtra("restaurant_name");
Toast.makeText(MainActivity.this, restaurant_name, Toast.LENGTH_LONG).show();
if(restaurant_name != null ) {
if (restaurant_name.equals("Romys")) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(26.89209, 75.82759), 15.0f));
mMap.addMarker(new MarkerOptions()
.position(new LatLng(26.89553, 75.82842))
.title("ROMYS"))
.showInfoWindow();
}
}else {
Toast.makeText(MainActivity.this,"It was not", Toast.LENGTH_LONG).show();
}
}
});
Use onNewIntent to update MainActivity. Kind of like this:
#Override
public void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
String restaurant_name = intent.getStringExtra("restaurant_name");
Toast.makeText(MainActivity.this, restaurant_name, Toast.LENGTH_LONG).show();
}
If you are displaying the alertbox from the MainActivity, consider adding flags to your intent to maintain the activity stack.
Related
In my app, there is a login activity first and a home activity. After logging in using volley and passing parameters to home activity in an intent, I'm able to start a foreground service that keeps the app running in background with notifications and getting back to home activity by clicking on the notification with the help of pending intent.
Now, I'm searching for how to open the app from main menu and accessing directly home activity with the pending intent of the foreground service. Maybe should I pass the parameters of the pending intent to the login activity and check them to redirect to home activity, but i'am stuck with this and don't understand.
Here is the login activity Page :
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.signIn);
// Login On Button Click
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();}
});
// THIS IS THE SOLUTION THAT I THOUGHT ABOUT : if the intent is not null open HomeActivity
Intent startinIntent = getIntent();
if (startinIntent.getStringExtra("userLogged") != null && !startinIntent.getStringExtra("userLogged").isEmpty()) {
String userLogged = startinIntent.getStringExtra("userLogged");
Intent startAgain = new Intent(this, HomeActivity.class);
tackBackWork.putExtra("userLogged", userLogged);
startActivity(startAgain);
Log.d("this is the ilue", userLogged);
}
}
private void login(){
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject object = new JSONObject();
try {
//input your API parameters
object.put("u",username.getText());
object.put("p",password.getText());
} catch (JSONException e) {
e.printStackTrace();
}
// Enter the correct url for your api service site
String url = getResources().getString(R.string.loginUrl);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String msg = response.getString("msg");
if(msg.contains("true")){
Intent loggedIn = new Intent(LoginActivity.this, HomeActivity.class);
loggedIn.putExtra("userLogged", response.toString());
startActivity(loggedIn);
finish();
}else{
Toast.makeText(getApplicationContext(), "Identifiants Incorrectes", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e){
Toast.makeText(getApplicationContext(), "erreur - 200 ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Volley on error listener", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
Here is the Home activity
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
String userLogged = getIntent().getStringExtra("userLogged");
}
#Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
public void onResume(){
super.onResume();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
protected void onStop() {
super.onStop();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onPause() {
super.onPause();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
}
Here is foreground Service Page :
public class ForegroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
String userLogged = intent.getStringExtra("userLogged");
Intent backToHomeActivity = new Intent(this, HomeActivity.class);
backToHomeActivity.putExtra("userLogged", userLogged);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, backToHomeActivity, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
// .setLargeIcon()
// .setColor()
.setContentIntent(pendingIntent)
.setContentText(input)
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I'm new to all of this. please help me.
The solution is to use SharedPreferences.
public class LoginActivity extends AppCompatActivity {
Button login;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.loginBtn);
sp = getSharedPreferences("login",MODE_PRIVATE);
if(sp.getBoolean("logged",false)){
goToMainActivity();
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToMainActivity();
sp.edit().putBoolean("logged",true).apply();
}
});
}
public void goToMainActivity(){
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
See the Tutorial below
https://medium.com/#prakharsrivastava_219/keep-the-user-logged-in-android-app-5fb6ce29ed65
I want to call camera intent in on Start Method and it works fine, but when i click on back button it does not go back from camera because Uri is empty. I want to go to previous Activity with clicking back button.
#Override
protected void onStart() {
super.onStart();
if (uri==null){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
Create a helper class with a static boolean variable like below,
public class HelperUtil
{
public static boolean isCameraActivityBackPressed;
}
And change your code little bit,
#Override
protected void onStart()
{
super.onStart();
if (uri == null)
{
if (HelperUtil.isCameraActivityBackPressed)
{
// this block will execute when ActivityCamera back is pressed and uri is null
startActivity(new Intent(this, ReplaceWithYourActivity.class));
} else
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
#Override
public void onBackPressed()
{
super.onBackPressed();
HelperUtil.isCameraActivityBackPressed = true;
Toast.makeText(ActivityCamera.this, "onbackpressed", Toast.LENGTH_LONG).show();
startActivity(new Intent(this, ActivityCamera.class));
finish();
}
I'm building a small app that scans barcodes and put them in a database (using ZXing library). After the scan is taken, and the barcode doesn't exist in the database I want to show a popup dialog that allows an user to enter the name manually.
The dialog works perfectly if it's invoked in an onClickListener, however when I try to put it in an 'if' statement within another method (which checks if the scan result is in the database) the dialog doesn't show.
What's strange, I put tags in the beginning of the method and at the end, both of them are shown in the log, but the alertdialog doesn't appear and it gets me back to the main activity without any error...
public void popUP (String barcode) {
Log.d(TAG, "method started");
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_input, null);
TextView tv = (TextView) mView.findViewById(R.id.textView2);
final EditText et = (EditText) mView.findViewById(R.id.item1);
Button bt1 = (Button) mView.findViewById(R.id.button2);
Button bt2 = (Button) mView.findViewById(R.id.button3);
final String code = barcode1;
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mydb.addNewItem(et.getText().toString(), code);
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
Log.d(TAG,"dialog shown");
}
And here is the method from which I try to inflate the popUP
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
final String barcode = scanResult.getContents();
if (scanResult != null) {
if(scanResult.getContents() == null) {
Log.d(TAG, "Cancelled Scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d(TAG, "SCANNED");
int rows = mydb.checkRows(barcode);
if (rows == -1){
Log.d(TAG, "popUP should appear");
popUP(barcode); //INVOKING THE ALERT DIALOG
} else {
Log.d(TAG, "found and attempting adding");
mydb.addItem(barcode, rows);
}
}
} else {
Toast.makeText(this, "oddal zero", Toast.LENGTH_LONG);
}
Intent intynt = new Intent(this, MainActivity.class);
startActivity(intynt);
}
I have created two activities:
Play
MorpionAI
decide and checkedplayer are both some integers.
How can I make my app so that when the button is clicked the app selects and calls one of the intents based on following:
if(decide==checkedplayer){
public void MorpionAI_Acitivity(View view) {
Clean();
deleteplayer();
Intent play = new Intent(this, MorpionAI.class);
startActivity(play);
}}
else{
public void Play_Activity(View view) {
Clean();
deleteplayer();
Intent play = new Intent(this, Play.class);
startActivity(play);
}}
I tried to do this using following code:
morpionbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (decide==checkedplayer){
Clean();
deleteplayer();
Intent play = new Intent(view.getContext(), Play.class);
startActivity(play);
}
else{
Clean();
deleteplayer();
Intent play = new Intent(view.getContext(), MorpionAI.class);
startActivity(play);
}
}
});
But it did not worked.
In your activity , defined a Context class field :
private Context mContext;
in the onCreate() function of this activity , initialize the field :
mContext = this;
then
morpionbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (decide == checkedplayer){
Clean();
deleteplayer();
Intent play = new Intent(mContext, Play.class);
mContext.startActivity(play);
}
else {
Clean();
deleteplayer();
Intent play = new Intent(mContext, MorpionAI.class);
mContext.startActivity(play);
}
}
});
Hope this helps.
I want my list to be displayed in new activity, but when I click the button I get the results in the same page, how do I get the results to be passed to new activity?
Button:
myList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AsyncTask().execute("");
}
});
onPostExecute:
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//Arrays.sort(avstand);
Intent intent = new Intent();
minValue = getMinValue(avstand);
if(result== false){
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
} else {
Adapter adapter = new Adapter(getApplicationContext(),R.layout.rad, myListe);
list.setAdapter(adapter);
}
}