How to connect mobile app to database - java

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

Related

Is there a way to reduce the size of the application?

I am facing a problem with the size of the application after I converted it from WebView to PdfView
Regardless of the size of the files in assets
The size of the application after exporting in PdfView size is 23 MB
In WebView 8 MB
Is it because of these plugins you put in gradle?
ndkVersion "22.1.7171670"
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
PdfView
import android.content.Intent;
import android.os.Bundle;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnRenderListener;
import androidx.appcompat.app.AppCompatActivity;
public class Web_Activity extends AppCompatActivity {
private AdView mAdView;
int pageNum;
PDFView pdfView;
String Title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
pdfView=(PDFView)findViewById(R.id.pdfView1);
final Intent intent = getIntent();
final String link = intent.getStringExtra("link");
pdfView.fromAsset(""+link)
.onRender(new OnRenderListener()
{
#Override
public void onInitiallyRendered
(int nbPages, float pageWidth, float pageHeight)
{
pdfView.fitToWidth();
}
}).load();
}
}
Is there a way to reduce the size of the application? knowing that the
application without these codes in webview is 8 megabytes, and after
converting webview to PDF-view it becomes 23 megabytes
If you generate your app as an .AAB file and upload to the playstore then it will create specific APKs for the device it is installing on, and they will be as small as possible.
If your app uses native files, there are specific files for each hardward architecture, if you use an APK it will have all the architecture files (all but one being unused) if you use an AAB then when the APK is generated it will only have the native file you need.
https://developer.android.com/guide/app-bundle
AAB is becoming the defactor standard instead of AAB.
If you want to calculate the APK size of an APK generated from an AAB you can use bundle tool: https://developer.android.com/studio/command-line/bundletool
Also the library you are using: https://github.com/barteksc/AndroidPdfViewer
Has a native library that is 16 meg
Why resulting apk is so big?
Android PdfViewer depends on PdfiumAndroid, which is set of native libraries (almost 16 MB) for many architectures. Apk must contain all this libraries to run on every device available on market. Fortunately, Google Play allows us to upload multiple apks, e.g. one per every architecture. There is good article on automatically splitting your application into multiple apks, available here. Most important section is Improving multiple APKs creation and versionCode handling with APK Splits, but whole article is worth reading. You only need to do this in your application, no need for forking PdfiumAndroid or so.
So using this PdfViewer your app will be 16meg bigger than your WebView Option. :-)
The library has not had changes pushed to it in over 2 years. It may be that it isn't up to date with the way AAB's figure out their splits. Your best bet would be to fork the library and see if updating the AGP version etc gives you any better results.

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!

Empty Open Street Map with OSMDroid & Android Studio

I have a problem while developing an Android App with a simple Open Street Map Acitivity. My AVD shows a empty map and the log says:
> W/System: ClassLoader referenced unknown path: /data/app/com.example.philipp.myapplication-1/lib/x86_64
> I/OsmDroid: Using tile source: Mapnik
> E/OsmDroid: unable to create a nomedia file. downloaded tiles may be visible to the gallery. open failed: ENOENT (No such file or
> directory)
> I/OsmDroid: sdcard state: mounted
This is my MainActivity:
import android.app.Activity;
import android.os.Bundle;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.views.MapView;
public class MainActivity extends Activity {
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapView map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
}
}
I haven't found anything at my online researches. And I'm not sure if this is a code or emulator problem..
Thanks for your help! If you need more information, let me know!
I might have a solution for you:
In my case the solution was to give permissions to use location and storage to my application in the android settings. Because i did not use the latest permission model, the application did not have the necessary permission to write storage and provide tiles.
//onde mostra a imagem do mapa
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
use this code within on create

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.

Android programming and using HTML parsers to pull category data from a Wikia.com page for use in a ListView

first off I was wondering if there are even HTML parsers that work with Android app programming or not, or if all I have access to is the html commands listed on the Android developers web site. The reason is I am making an app that allows you to access the Zelda Wikia and instead of hard coding everything such as the titles of the video games I wanted to go ahead and pull the names using the MediaWiki API, the command I found was this:
http://zelda.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Games&cmlimit=500
This returns all of the titles in HTML formatting and the only way that I can think to pull what I need from what this returns is using an HTML parser, but I am not sure that there is one that works with Android programming and if so how I would even go about pulling what I need from this. After I get the data from this I want to display it in a ListView and when the title is clicked it will take the user to the Wikia for that specific title in a WebView. Is this the way I should be going about this or are there any other recommendations that anyone has, please I really need help. The rest of the code is as follows just incase anyone wants to see what I have:
package com.lvlup.kikurself.zeldatest;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class zeldaGames extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "The Legend of Zelda", "Zelda II: The
Adventure of Link", "The Legend of Zelda: Ocarina of Time",};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
final ListView zeldaList = getListView();
zeldaList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long thisID)
{
Object o = (zeldaList.getItemAtPosition(position));
String gameName_temp = (o.toString());
Intent newIntent = new Intent(v.getContext(), gameDisp.class);
newIntent.putExtra("tempG", gameName_temp);
startActivity(newIntent);
}
});
Thank you for taking the time to read this.
I wouldn't use a parser on the phone. Before you know, the owner of the page could come up with a new layout, ruining your app.
Instead, I would build a webservice (PHP with DomXML is an exelent choice) which parses the given site, and returns file in XML, JSON or other format. And then I would write an app to use the parser webservice as a datasource.
In this way, you will have a lot more computer power. You only have to maintain one instance of the parser, an you know it works on any device, that has downloaded your app.
Maybe sounds like a lot of work, but trust me on this - you'll be better of.
Personal and profesional experience
Append &format=xml to your URL to get machine-readable data. See MW help on API formats at https://www.mediawiki.org/wiki/API:Data_formats and general API help at https://www.mediawiki.org/wiki/API

Categories