ANDROID STUDIO How to go back to application from settings - java

I got some trouble with android studio I work in a company who has a web application so I worked on IOS application it was pretty easy but now I worked on Android and I'm not able to do a simple return to the application.
This the visual legacy :
When you open the application it answers you to allow some permission to the app :
[Popup to authorize permission]
https://i.stack.imgur.com/Uz9Ox.png
Then you go to the settings :
[Settings] https://i.stack.imgur.com/oqlfG.png
As you can see we implement additional settings to enter user ids ( mail, password ) :
[Additional settings ] https://i.stack.imgur.com/zn8Ll.png
You can see that there is a button below the inputs I want it to returns to the application but when I'm putting this code
Preference myPref = findPreference("backto");
myPref.setOnPreferenceClickListener(preference -> {
startActivity(new Intent(getContext(), MainActivity.class));
return true;
});
It doesn't send me to the application it creates a new instance of the application directly in the additional settings.
How can I make a function that send me to the app and not create a new instance ?
There is my additional settings class:
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
/**
* A simple {#link Fragment} subclass.
*/
public class SettingsFragment extends PreferenceFragmentCompat {
MainActivity mainActivity;
#Override
public void onCreatePreferences(#Nullable Bundle savedInstanceState, #Nullable String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
Preference myPref = findPreference("backto");
myPref.setOnPreferenceClickListener(preference -> {
startActivity(new Intent(getContext(), MainActivity.class));
return true;
});
}
}

If you want to request permissions from your app, the proper way is through Intent and then you handle the code in onRequestPermissionsResult. There is no need to direct the user to the settings
See these tutorials for more info. Just keep in mind that Google now has a new policy about "sensitive permissions", some of them may not be approved when uploaded on Google Play
Link 1,
Link 2,
Link 3

Related

Passing string literals to stored procedure in android studio with EditText?

Second post here, the first one was extremely helpful so thank you for those that contributed. I will try to be concise with the issue I'm having. I am using android studio in intellij to develop an application. Part of the functionality of the app is a fragment that accepts a new username input from the end user, and then stores that username into my database (a preexisting database that has been linked to intellij). I am new to java and only in the last couple days started to change from creating UI with swing and awt, to xml files. My understanding is that xml files are data descriptors and useful for creating static objects/widgets while the .java files use java to create behaviors for the objects by referencing their IDs created in the xml file. Now comes the confusing part for me, and forgive me if this seems like a no brainer, as I'm pretty new to all this- I have "piggybacked" off a base shell for a android app, and as best as I can tell, setOnClickListener is essentially the android java version of action listeners. I added to the method that essentially took a button and navigated from one fragment to the next, with code that connects to the database, and then executes the stored procedure presumably when the "next"/"submit" button is clicked. Now here's the catch: obviously when a submit button is clicked, there is no user defined username that gets passed into the stored procedure, so obviously it won't work. The problem is, the TextEdit text field that I created is created in an xml file with no way to reference it or manipulate it in the java code, yet it accepts "text" parameters and works fine in the emulator. Obviously I want the stored procedure to take the user inputs in that text field and store it as a new username in the database, but since xml just describes data, and there isn't any defined text field in the java code, I'm at a loss for how to accomplish this task. I can't just write up an action listener and attach it to the xml id of the TextEdit because there isn't anything in the xml file that explains where the actual typed characters are! I know, higher level programming issues. Can anyone help explain how to do what I'm trying to do? Preferably as much as possible in laymans terms. Here is the code:
package com.example.callit;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.sql.*;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
public class FirstFragment extends Fragment {
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
String sqldatabase = "//database connection url";
try {
Connection con = DriverManager.getConnection(sqldatabase);
CallableStatement cs = con.prepareCall("{EXEC [dbo].[CreateUser] #UserName = N'Dog', #UserID = #UserID OUTPUT}");
cs.execute();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
});
}
}
I included it in case there was something inherently wrong with the connection to the database code (I also am aware that I should disconnect from the database as well). I would like to note that the code runs without errors, it just doesn't do what it should (for the reasons I explained above). Any help would be greatly appreciated!

Start Activity from Service in Android 10

please note that problem might be related to Android 10
Im trying to start a new Activity from myInAppMessagingService, but i got null pointer exception un startActivitys context parameter every time.
So here is my Service code :
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.firebase.inappmessaging.FirebaseInAppMessagingClickListener;
import com.google.firebase.inappmessaging.model.Action;
import com.google.firebase.inappmessaging.model.CampaignMetadata;
import com.google.firebase.inappmessaging.model.InAppMessage;
import viaapp_v2.systems.webview_activity.webview_base;
public class MyFirebaseInAppMessaging extends Service implements FirebaseInAppMessagingClickListener {
String TAG = "MyFirebaseInAppMessaging";
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void messageClicked(#NonNull InAppMessage inAppMessage, #NonNull Action action) {
// Determine which URL the user clicked
String url = action.getActionUrl();
Log.d(TAG, "Popup URL :"+url);
// Get general information about the campaign
CampaignMetadata metadata = inAppMessage.getCampaignMetadata();
Log.d(TAG, "metadata :"+metadata);
try{
startActivity(
new Intent(MyFirebaseInAppMessaging.this, webview_base.class)
.putExtra("web_url", url)
);
}catch(Exception e){
e.printStackTrace();
}
}
}
I got error in "startActivity(..)" line because of 1st parameter, context. I tried everything - getApplicationContext(), MyFirebaseInAppMessaging.this or just simply "this" but nothing works.
I read a restrictions provided by Android Developers, but i couldnt figure out anything new.
Otherwise the app works perfectly - webview_base class works as it should, so does everything else, including myInAppMesaging Services listener. Its just that one context in startActivity() which stops me.
Thanks for any help.
--Update on Sep 7
After playing around with permissions, flags ect. i noticed that nothing works. Newer Android OS opens an web overly over the app, but older Android OS just crashes without any specific crash report. Thats weird.
Try below code , it will work..
you have to add FLAG- FLAG_ACTIVITY_NEW_TASK
Intent myIntent = new Intent(this, webview_base.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(myIntent);
If your app is not visible and has not been visible for a while and you don't want to use a notification, it will not be allowed in Android 10, except if
The app has been granted the SYSTEM_ALERT_WINDOW permission by the user.
(From the restrictions page mentioned in the question)
So that's an option for Android 10.
It's not enough to list the SYSTEM_ALERT_WINDOW in AndroidManifest.xml. You also need user to give the app "Draw over other apps" permission. Check here how to do that easily.

How to connect mobile app to database

I created a basic barcode scanner app with Java and Android Studio (on my Mac paradoxically). In this app, I simply uploaded (manually) some photos of barcodes to Android Studio in the .../app/src/main/res/drawable folder from my desktop and then I am sending one of these photos each time to Google Mobile Vision Barcode API. I receive from the API the data represented from the barcode and I simply print the data on the screen of the Android emulator.
The MainActivity.java script of this app is the following:
package *********************;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.SparseArray;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageView myImageView = (ImageView) findViewById(R.id.imgview);
Bitmap myBitmap = BitmapFactory.decodeResource(
getApplicationContext().getResources(),
R.drawable.image);
myImageView.setImageBitmap(myBitmap);
TextView txtView = (TextView) findViewById(R.id.txtContent);
BarcodeDetector detector =
new BarcodeDetector.Builder(getApplicationContext())
.setBarcodeFormats(Barcode.DATA_MATRIX | Barcode.QR_CODE | Barcode.CODE_128)
.build();
if(!detector.isOperational()){
txtView.setText("Could not set up the detector!");
return;
}
Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
SparseArray<Barcode> barcodes = detector.detect(frame);
Barcode thisCode = barcodes.valueAt(0);
txtView.setText(thisCode.rawValue);
}
Now I want to use the retrieved data from the Barcode API, send them to (a server and to) a database and retrieve some details stored in this database about the product that has this barcode.
What is the most appropriate way to make my Java app to communicate with a database?
Personally, I am pretty confident in creating a MySQL database and sending back and forth data with PHP.
However, I am not really sure how to connect a script written in Java (which scans barcodes) to a database.
It really depends on your use case.
Possibilities:
1- Make your own database (Sqlite) in your Android App. This means you have to synchronize via web services, with your server's database, whenever you see fit.
Steps:
a) Use an ORM to connect to your local database and to relational map your tables with your classes.
b) Use web service to synchronise your classes (eg. Retrofit) with your server's database, via an API.
2- Only use the 'b' part of the 1-st step to save your data to remote database, on-fly (as soon as data is submmited)
So you actually CAN (b), but connecting to remote database immediately as the data gets submitted is really bad(in my opinion). For many reasons. Take a look here.
In the end, it all comes down to your choice and the best suit for your app's use-case.
Best

How to display tweets from a twitter account and tweet that same account from an android app using twitter4j?

I'm currently trying to make an app that should pull the last 10 or 20 tweets from a twitter account (not mine, but a third party), and display them. I also want to be able to let user's post a tweet to this person and follow them on twitter if they don't already.
I've been looking at tutorials the last few hours and really cannot wrap my head around it. I've already imported the twitter4j-core-4.0.1.jar into my project.
In my MainActivity.java, I have a method that responds to a button:
public void twitter(View view)
{
//Create an intent and send it the twitter activity class
Intent twitterActivity = new Intent(this, TwitterActivity.class);
startActivity(twitterActivity);
}
So what I want to know is, how do I set up the view to display the tweets from the a twitter account, as well as allow a user to tweet them, and/or follow them.
This is what I have so far in my TwitterActivity.java:
import java.util.List;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
public class TwitterActivity extends Activity
{
// I think I need to create some global variables here for the consumer key and consumer secret.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter);
setupActionBar();
// I assume the twitter set up happens here.
}
.....
}
I guess you will have to use JSONObject and JSONArray to get it work.
Use this uri to get the tweets:
http://api.tweeter.com/1/statuses/user_timeline.json?screen_name=
Also tweets can be obtained from using following code:
new Read().execute("text")
where text has the actual tweet.
You can then use StringBuilder and append the username to the URI as mentioned above.

Trying to make a Adapter class to choose .Java file depending on firmware version

What I did was create two .java files. One that can compile and run on a 1.5 phone (SDK3) and then one that works on 2.0(SDK5) So for this example i'll call the 1.5 file ExampleOld and the new one Example. I was wondering if i just made activity like this if it would work sort of like a "portal" and pick the activity to load depending on the SDK so there is no crash or compile errors. Are there any changes I should make to my code? Maybe anyone out there that's had to do this before. thanks!
package com.my.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
public class ExamplePortal extends Activity {
int sdk=new Integer(Build.VERSION.SDK).intValue();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (sdk<5) {
Intent v = new Intent(this, ExampleOld.class);
startActivity(v);
}
else {
Intent v = new Intent(this, Example.class);
startActivity(v);
}
}
}
What you're doing (correct me if I'm wrong) is trying to maintain backwards compatibility while making use of new APIs if the user is running a newer android version. The best way to do this is to follow the tutorial Google posted here. This avoids any verification issues and is really the best way to do stuff imho.
I would put this decision in a Factory Class to avoid having these if-else statements all over the codebase.

Categories