How to get JSON data from localhost in Android Studio (RESTful API) - java

So i've followed some tutorial on YT on how to get JSON object and JSON array of objects from website using URL and it worked. The code is below. Now, i've tried doing the exact same thing with URL of my localhost database, but it didn't work. I didn't get any errors or anything, and i have no idea what is the problem. I'm trying to do some RESTful API, in which the code in java is creating table with data in database, and it works perfectly, it's just that i cannot connect android app to it.
package com.example.motto_app;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
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 com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
RadioGroup RG;
RadioButton bA, bB, bC, bD;
TextView tA, tB, tC, tD, tQ;
Button bN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assigning variables to objects in layout
RG = findViewById(R.id.radioGroup);
bA = findViewById(R.id.answerAButton);
bB = findViewById(R.id.answerBButton);
bC = findViewById(R.id.answerCButton);
bD = findViewById(R.id.answerDButton);
tA = findViewById(R.id.answerAText);
tB = findViewById(R.id.answerBText);
tC = findViewById(R.id.answerCText);
tD = findViewById(R.id.answerDText);
tQ = findViewById(R.id.textQuestion);
bN = findViewById(R.id.NextButton);
//on-click listeners
bN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://localhost:8080/quiz";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String question = "";
try {
JSONObject cityInfo = response.getJSONObject(0);
question = cityInfo.getString("question");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Question: " + question, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Something wrong", Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
}
});
bA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "AAA", Toast.LENGTH_SHORT).show();
}
});
bB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "BBB", Toast.LENGTH_SHORT).show();
}
});
bC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "CCC", Toast.LENGTH_SHORT).show();
}
});
bD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "DDD", Toast.LENGTH_SHORT).show();
}
});
}
}
Now i just want to add that the only thing that i've changed from the original code from YT is URL and variable names. The code worked perfectly with standard URL. Here is how my localhost looks: http://localhost:8080/quiz

By localhost do you mean the PC you're programming on, or the android device itself?
In the case you mean the Android device itself- you would never use a RESTful service here. You'd just make direct DB calls.
In the case you meant your PC- that isn't localhost. Not to the device. You need to use the actual IP of the device. Even if you're using an emulator, the emulator thinks its a separate machine and has its own IP address- localhost would only go to the emulator. And if its an actual device and not an emulator, you need to have your WIFI set up to allow traffic to that port (assuming your PC is on the same wifi network as your device. If not, its even more complicated).

Related

How can I Register and Store Data in Firebase Database - Android Studio | Firebase

I have a registration system in my project where users can create an account. But how can I put their records in Firebase Realtime Database?
By hitting the register button, the account is created and I also want the records to store in the firebase database.
package com.example.sampleapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Register extends AppCompatActivity {
EditText regFullName, regEmail, regPass, confPass;
Button regBtn, gotoLogin;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
regFullName = findViewById(R.id.regFullName);
regEmail = findViewById(R.id.regEmail);
regPass = findViewById(R.id.regPass);
confPass = findViewById(R.id.confPass);
regBtn = findViewById(R.id.regBtn);
gotoLogin = findViewById(R.id.gotoLogin);
fAuth = FirebaseAuth.getInstance();
//Back to Login Page
gotoLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code for opening new Classes
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
});
//Register Button
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Extracting Data from the forms
String FullName = regFullName.getText().toString();
String Email = regEmail.getText().toString();
String Password = regPass.getText().toString();
String ConfirmPass = confPass.getText().toString();
if (FullName.isEmpty()){
regFullName.setError("Full Name is Required.");
return;
}
if (Email.isEmpty()){
regEmail.setError("Email is Required.");
return;
}
if (Password.isEmpty()){
regPass.setError("Password is Required.");
return;
}
if (ConfirmPass.isEmpty()){
confPass.setError("Confirm Your Password.");
return;
}
//Confirming if the Password is not correct
if (!Password.equals(ConfirmPass)){
confPass.setError("Password Do Not Match.");
return;
}
//Registering the user
Toast.makeText(Register.this,"Data Validated",Toast.LENGTH_SHORT).show();
fAuth.createUserWithEmailAndPassword(Email,Password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
//Send user to next page
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
I tried doing the methods in youtube videos but it won't work. I am able to create an account but the records are not inserting to the database
I am able to create an account but the records are not inserted into the database.
When you call FirebaseAuth#createUserWithEmailAndPassword(String email, String password) it:
Tries to create a new user account with the given email address and password. If successful, it also signs the user into the app.
But this operation doesn't automatically insert user data into the database. If you need that, you have to do it yourself. So you can solve that in two ways, you either use the following lines of code on the client when the authentication is successful:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Map<String, Object> user = new HashMap<>();
user.put("uid", uid);
//Add other user data
DatabaseReference usersRef = db.child("users");
usersRef.child(uid).setValue(user).addOnCompleteListener(/* ... /*);
Or you can trigger a function when the authentication is successful.

how to make barcode work with device keys?

I am trying to code an inventory app that can work on UROVO DT40 device. I don't know how to code the barcode scanner so that it will work on keystroke and send the result to edittext. I also want to save the data from the adapter and be able to read from a PC. I am still a rookie so I don't know if am doing it the right way. I need some help please. Thanks!!
here's some of the code
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {ArrayList<String>
listitems = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextInputEditText input = findViewById(R.id.textInputEditText);
TextInputEditText input1 = findViewById(R.id.textInputEditText1);
ListView listview = findViewById(R.id.listView);
Button saveBtn = findViewById(R.id.saveBtn);
Button btn_annuler = findViewById(R.id.btn_annuler);
Button OK = findViewById(R.id.btn3);
Button btn2 = findViewById(R.id.btn2) ;
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,listitems);
listview.setAdapter(adapter);
input.setShowSoftInputOnFocus(false);
input1.setShowSoftInputOnFocus(false);
OK.setOnClickListener(v -> {
listitems.add(Objects.requireNonNull(input.getText()).toString() + ';' + Objects.requireNonNull(input1.getText()).toString());
adapter.notifyDataSetChanged();
input.setText("");
input1.setText("");
});
btn_annuler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
input.setText("");
input1.setText("");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.clear();
}
});
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!adapter.toString().equals(""))
{
String data = adapter.toString();
writeToFile(data);
Toast.makeText(MainActivity.this, "Vidage éffectué!", Toast.LENGTH_LONG).show();
}
}
});
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("ficGloba.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
There are code samples on the Urovo github page for the Android SDK, specifically also one for the Scanner
Steps 1 to 4 from from the ScannerManagerDemo.java javadoc describe how you have to setup the Scanner:
1.Obtain an instance of BarCodeReader with ScanManager scan = new ScanManager().
2.Call openScanner to power on the barcode reader.
3.After that, the default output mode is TextBox Mode that send barcode data to the focused text box. User can check the output mode
using getOutputMode and set the output mode using switchOutputMode.
4.Then, the default trigger mode is manually trigger signal. User can check the trigger mode using getTriggerMode and set the trigger mode
using setTriggerMode.
for full completeness, the extracted javacode:
private void initScan() {
mScanManager = new ScanManager();
boolean powerOn = mScanManager.getScannerState();
if (!powerOn) {
powerOn = mScanManager.openScanner();
if (!powerOn) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Scanner cannot be turned on!");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog mAlertDialog = builder.create();
mAlertDialog.show();
}
}
initBarcodeParameters();
}
That should give you enough to get cracking. Godspeed.

Inactive input connection

On running this app on an emulator it is performing as expected but when run on an actual android device it is not producing desired result and is showing the warning "getExtractedText on inactive InputConnection" in the logs. It's a chatbot application where i'm performing get request on an api with retrofit2 library.
package com.example.chatbot;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView chatBotRV;
private MessageAdapter messageAdapter;
private FloatingActionButton sendButton;
private EditText queryText;
private String USER_KEY = "USER";
private String BOT_KEY = "CHAT_BOT";
private Retrofit retrofit;
private APIservice apIservice;
private ArrayList<ChatModel> chatModelArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chatBotRV = findViewById(R.id.chat_bot_rv);
sendButton = findViewById(R.id.send_button);
queryText = findViewById(R.id.chat_ev);
chatModelArrayList = new ArrayList<>();
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!queryText.getText().toString().isEmpty()){
String message = queryText.getText().toString();
queryText.setText(null);
getMessage(message);
}else{
Toast.makeText(MainActivity.this, "Please enter your message :)", Toast.LENGTH_SHORT).show();
return;
}
}
});
messageAdapter = new MessageAdapter(chatModelArrayList, MainActivity.this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
chatBotRV.setLayoutManager(layoutManager);
chatBotRV.setAdapter(messageAdapter);
}
private void getMessage(String msg){
ChatModel chatModel_user = new ChatModel(msg, USER_KEY);
chatModelArrayList.add(chatModel_user);
messageAdapter.notifyDataSetChanged();
String url = "MY_API_URL"+msg;
String BASE_URL = "http://api.brainshop.ai/";
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apIservice = retrofit.create(APIservice.class);
Call<MessageModel> call = apIservice.getMessage(url);
call.enqueue(new Callback<MessageModel>() {
#Override
public void onResponse(Call<MessageModel> call, Response<MessageModel> response) {
if(response.isSuccessful()){
MessageModel model = response.body();
chatModelArrayList.add(new ChatModel(model.getCnt(), BOT_KEY));
messageAdapter.notifyDataSetChanged();
}else{
Toast.makeText(MainActivity.this, "Some error on our side", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<MessageModel> call, Throwable t) {
chatModelArrayList.add(new ChatModel("Please revert your query", BOT_KEY));
messageAdapter.notifyDataSetChanged();
}
});
}
}
The InputConnection is overwhelmed by requests to clear the text. I tried modifying the code to check for text length before trying to clear it:
if (editText.length() > 0) {
editText.setText(null);
}
This helps mitigate the problem in that pressing the send button rapidly no longer causes the stream of InputConnectionWrapper warnings. However, this is still prone to problems when the user rapidly pressing the send button when the app is under sufficient load, etc.
There's another way to clear text: Editable.clear(). with this I don't get warnings at all:
(like getExtractedText on inactive InputConnection)
try this:
if (editText.length() > 0) {
editText.getText().clear();
}
Note that should you wish to clear all input state and not just the text (autotext, autocap, multitap, undo), you can use TextKeyListener.clear(Editable e).
if (editText.length() > 0) {
TextKeyListener.clear(editText.getText());
}

2 Edit text get currency format(###,###,###) and mines but (crash when clicked on btn mines)

here is the java code :
package com.aliabbasi.mytamrin;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
public class full extends AppCompatActivity {
EditText full_payment, cash_payment,remain_payment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full);
Toast.makeText(this, "مقادیر را با دقت وارد کنید", Toast.LENGTH_LONG).show();
Button btn_cancel = findViewById(R.id.btn_cancel);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent btn_cancel = new Intent(full.this, MainActivity.class);
startActivities(new Intent[]{btn_cancel});
}
});
try {
Button remain_check = findViewById(R.id.remain_btn);
remain_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
full_payment = findViewById(R.id.edt_full_payment);
cash_payment = findViewById(R.id.edt_cash_payment);
remain_payment = (EditText) findViewById(R.id.edt_remain);
Float a = Float.parseFloat(full_payment.getText().toString());
Float b = Float.parseFloat(cash_payment.getText().toString());
Float s = a - b;
String r = Double.toString(s);
remain_payment.setText(r);
}
});
} catch (Exception e) {
Toast.makeText(this, "خطایی رح داده" + e, Toast.LENGTH_LONG).show();
}
try {
EditText editText= (EditText) findViewById(R.id.edt_full_payment);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}
try {
EditText editText= (EditText) findViewById(R.id.edt_cash_payment);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}
/*try {
EditText editText= (EditText) findViewById(R.id.edt_remain);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}*/
}
}
i try the double variable
there is no Error but program crashed when i press the remain_btn.
i check the Debug and find out there is a problem with this:
at com.aliabbasi.mytamrin.full$2.onClick(full.java:45).
andNumberFormatException** but IDK how to solve it.**
and i really like to know how fix this becase i stuck in this about 2 days...
thanks for reading ...
wish the best
code imag
You can do something like this. Remove that comma.
Float a = Float.parseFloat(full_payment.getText().toString().replace(",", ""));

Can't run ibeacon app but has no error in the code

I'm doing a project with ibeacon using Eclipse to build an APP , I import some codes from Android beacon library for detecting UUID , with no error in the codes , I try to open the apk on HTC device, but failed to open the App .
Here is my code. Any help or suggest is appreciated.
package com.example.goooooood;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.MonitorNotifier;
import org.altbeacon.beacon.Region;
import android.app.Activity;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public abstract class MainActivity extends Activity implements BeaconConsumer {
protected static final String TAG = "MonitoringActivity";
private BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager = BeaconManager.getInstanceForApplication(this);
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
// beaconManager.getBeaconParsers().add(new BeaconParser().
// setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.i(TAG, "I just saw an beacon for the first time!");
}
#Override
public void didExitRegion(Region region) {
Log.i(TAG, "I no longer see an beacon");
}
#Override
public void didDetermineStateForRegion(int state, Region region) {
Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);
}
});
try {
beaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
} catch (RemoteException e) { }
}}
Here is the logcat.
logat part 1 of the code
logcat part 2 of the code

Categories