I'm making OTP based registrations how do I validate my OTP number please help.
here are 2 scripts
1 is a validation activity
2 is an async task running ok http req
3 there is one more activity which takes a user phone number and sends OTP SMS
which is working fine
I just wanna check if OTP on my edit text matches with message user received
package com.example.test2;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
class Verifyotp extends AsyncTask<String, Void, Void> {
public static String string;
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("mobile_no", MainActivity.phoneNo)
.addFormDataPart("otp", OTP_activity.OTP)
.build();
Request request = new Request.Builder()
.url("http://127.0.0.1:8000/api/verifyotp")
.method("POST", body)
.addHeader("Accept", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
string = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.example.test2;
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.TextView;
import android.widget.Toast;
import java.util.Objects;
public class OTP_activity extends AppCompatActivity {
public static String OTP;
TextView mssg;
EditText ED;
Button ver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_activity);
mssg = (TextView) findViewById(R.id.txtmssg);
ver = (Button) findViewById(R.id.verify);
ED = (EditText)findViewById(R.id.otp);
mssg.setText("We have sent you an SMS on " + MainActivity.phoneNo + " with 4 digit verification code.");
ver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OTP = ED.getText().toString();
Verifyotp chk= new Verifyotp();
chk.execute();
int i = Verifyotp.string.length();
if (i < 20){
Toast.makeText(getApplicationContext(),
"please try again.", Toast.LENGTH_LONG).show();
}
else {
Intent in = new Intent(OTP_activity.this, Home_Acivity.class);
startActivity(in);
}
}
});
}
}
Any help is appreciated
You Could Use Firebase OTP Authentication For This Work.
Related
I'm having trouble getting data from OpenSubtitles api. I have looked at many examples for java and python. Below is the class I'm trying to use to authenticate with OpenSubtitles api. After that I want to make request that will return a list of items I can pass to my recyclerview.
package com.shivito.subreader;
import android.app.DownloadManager;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class OpensubsRequest {
static String username;
static String password;
static String language;
static String useragent;
#RequiresApi(api = Build.VERSION_CODES.O)
public static void makerequest(){
Thread thread = new Thread() {
#Override
public void run() {
try {
Log.d("here","nope");
URL Opensubs = new URL("https://api.opensubtitles.org/xml-rpc");
URL url = new URL("https", "api.opensubtitles.org", 443, "/xml-rpc");
URLConnection uc = Opensubs.openConnection();
Log.d("working",uc.toString());
uc.addRequestProperty("username",username);
uc.addRequestProperty("password",password);
uc.addRequestProperty("language",language);
uc.addRequestProperty("useragent",useragent);
uc.connect();
Log.d("anythingnow", String.valueOf(uc.getAllowUserInteraction()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
Okay so in the above class I am trying to send my login information to the api then I try to check if it was successful by reading the response from(uc.getAllowUserInteraction()). Up to this point it always says false. Of course I'm likely not doing this right and I hope someone can point me in the right direction. Thank you!!
I am beginner in android development.
I used volley library for HTTP connections
The program is supposed to load data from the server into a list called listItems and push it to a recyclerview. The program works fine but I can't make access to list values outside the procedure loadRecyclerView
This is the code:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private ArrayList<ListItem> listItems;
private TextView dateTextView;
private static final String URL_DATA = "http://10.0.2.2:8080/json/csv.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateTextView = (TextView) findViewById(R.id.Date);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateTextView.setText("Date:" + simpleDateFormat.format(new Date()));
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.hasFixedSize();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerView();
// I want to access values of the list right here
Log.i("list", "onCreate: "+this.listItems.size());
}
private void loadRecyclerView() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Chargement...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
URL_DATA,
// this is an anonymous class, make it a public class and instantiate from it
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String salle = object.getString("salle");
String matiere = object.getString("matiere");
String groupe = object.getString("groupe");
String nomEnseignant = object.getString("nomEnseignant");
String typeSeance = "";//object.getString("typeSeance");
String seance = ""; //object.getString("seance");
String regime = "";//object.getString("regime");
ListItem listItem = new ListItem(matiere,typeSeance, groupe, salle, nomEnseignant,regime,"",seance,simpleDateFormat.format(new Date()));
listItems.add(listItem);
}
adapter = new RecyclerViewAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
Log.i("list", "onResponse: "+listItems.size());
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
if (error instanceof NetworkError) {
Toast.makeText(getApplicationContext(),"Cannot connect to Internet...Please check your connection!",Toast.LENGTH_SHORT).show();
}
else if (error instanceof ServerError) {
Toast.makeText(getApplicationContext(),"The server could not be found. Please try again after some time!!",Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
Toast.makeText(getApplicationContext(),"AuthFailureError",Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
Toast.makeText(getApplicationContext(),"Parsing error! Please try again after some time!!",Toast.LENGTH_SHORT).show();
} else if (error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(),"NoConnectionError",Toast.LENGTH_SHORT).show();
} else if (error instanceof TimeoutError) {
Toast.makeText(getApplicationContext(),"Connection TimeOut! Please check your internet connection.",Toast.LENGTH_SHORT).show();
}
}
}
);
Log.i("list", "size: "+listItems.size());
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I read on google that anonymous class can change attributes but the change is not maintained outside it.
Any solution?
String request is executed in the background thread. It finishes after your attempt to check the list size, so the list is empty yet. You will have filled list in onResponse() callback.
I am trying to add a for loop or while loop for method getuserDetailWhileLoop(); but i am having a hard time figuring out on how to do it. This code suppose to show json object to text view and text view has scroll view in it. However when i ran the code the while loop is not working and only show 1 object. I need the while loop to show multiple object. How will i be doing that? Thanks.
package com.demo.myblog.profile;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.demo.myblog.R;
import com.demo.myblog.volley.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class UserProfile extends AppCompatActivity {
private String ID,NAME,EMAIL,CREATED_DATE, ID2;
private String appURl, appURl2;
Activity mContext = this;
TextView mId,mName,mEmail,mDate, mid2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile2);
mId = findViewById(R.id.txt_Id);
mid2 = findViewById(R.id.textView5);
mName = findViewById(R.id.txt_Name);
mEmail = findViewById(R.id.txt_Email);
mDate = findViewById(R.id.txt_Data);
Intent data = getIntent();
EMAIL = data.getStringExtra("email");
appURl = "url here";
appURl2 = "url2 here";
getUserDetail();
getuserDetailWhileLoop();
}
private void getuserDetailWhileLoop()
{
if (EMAIL.isEmpty()){
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setMessage("Email cannot be empty");
alert.setCancelable(false);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
else{
StringRequest stringRequest = new StringRequest(Request.Method.GET,appURl2, new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try
{
JSONObject jo = new JSONObject( response );
for(int i =0 ;i < jo.length(); i++)
{
ID2 = jo.getString( "id" );
//NAME = jsonObject.getString("username");
//EMAIL = jsonObject.getString("user_email");
//CREATED_DATE = jsonObject.getString("created_date");
//sonObject = jsonObject.getJSONObject( "id" );
mid2.setText( ID2 );
//mName.setText(NAME);
//mEmail.setText(EMAIL);
//mDate.setText(CREATED_DATE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I like to use for loops over while loops, because with a for loop you're able to check the progress of the loop.
In this case it is best to use a for loop, just like you already did.
Can you post a example response of the StringRequest?
[EDIT]
You forgot to add the counter 'i', your for loop is fine.
JSONObject obj = jo.getJSONObject(i);
obj.getString("id");
I think this is the solution to your problem.
I am working on an application that would send an image with 2 strings but I am not as experienced in this field so i was lost for the last day or two trying to figure this out as i started with a script but didn't work for me
here is the part of script that i worked on which has a bit PHP behind and just show an image in my activity once it's chosen form the gallery with a bit of logic that i understood but didn't really work for me
that's my java code :
package com.example.tuteur;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class ajouter_photo extends AppCompatActivity implements View.OnClickListener {
ImageView upload_img;
EditText img_text;
EditText img_titre;
Button img_but;
private static final int result_load_img = 1;
private static final String server = "http://192.168.1.3/pfe/saveImg.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ajouter_photo);
upload_img=findViewById(R.id.photo_upload);
img_but=findViewById(R.id.upload_button);
img_text=findViewById(R.id.upload_text_corps);
img_titre=findViewById(R.id.upload_text_title);
upload_img.setOnClickListener(this);
img_but.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case(R.id.photo_upload):
Intent galleryIntent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,result_load_img);
break;
case(R.id.upload_button):
Bitmap image =((BitmapDrawable) upload_img.getDrawable()).getBitmap();
new uploadimg(img_text.getText().toString(),image,img_titre.getText().toString());
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if( requestCode==result_load_img && resultCode==RESULT_OK && data != null){
Uri selectedimg = data.getData();
upload_img.setImageURI(selectedimg);
}
}
private class uploadimg extends AsyncTask<Void , Void , Void> {
String text;
Bitmap image;
String titre;
public uploadimg(String text, Bitmap image,String titre) {
this.text = text;
this.image = image;
this.titre=titre;
}
#Override
protected Void doInBackground(Void ... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100,byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("text",text));
dataToSend.add(new BasicNameValuePair("image",encodedImage));
dataToSend.add(new BasicNameValuePair("titre",titre));
HttpParams httpRequest = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequest);
HttpPost post =new HttpPost(server);
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"erreur" , Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getApplicationContext(),"L'image est envoyé",Toast.LENGTH_SHORT).show();
}
}
private HttpParams getHttpRequestParams()
{
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,1000*30);
HttpConnectionParams.setSoTimeout(httpRequestParams,1000*30);
return httpRequestParams;
}
}
and this is my PHP which just store my image in the server not a data base it was test before I would try with blob
<?php
$name = $_POST["text"];
$image=$_POST["image"];
$decodedImage = base64_decode("$image");
file_put_contents("pictures". $name . ".PNG" , $decodedImage);
?>
I have written a code to access the below api and get the corresponding values of namaz timings, but the onResponse method is not getting invoked. I have given internet permissions in the android manifest file. I am new to Android, please help.
While Installing app is not asking for internet permissions though I mentioned it in manifest file.
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class NamazTiming extends AppCompatActivity {
private TextView fazarId, zoharid, asarid, magribid, ishaid, location;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.namaz_timing);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Namaz Timings");
fazarId = findViewById(R.id.fazarid);
zoharid = findViewById(R.id.zoharid);
asarid = findViewById(R.id.asarid);
magribid = findViewById(R.id.magribid);
ishaid = findViewById(R.id.ishaid);
location = findViewById(R.id.location);
Button locationbutton = findViewById(R.id.locationbutton);
mQueue = Volley.newRequestQueue(this);
locationbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
//String loc = location.getText().toString().trim();
String url ="https://muslimsalat.com/uravakonda.json?key=ba8d0b5ba55c6db3cebbe3fefd6090f8";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(NamazTiming.this, "Entered onresponse", Toast.LENGTH_SHORT).show();
try {
Toast.makeText(NamazTiming.this, "Entered into TRY", Toast.LENGTH_SHORT).show();
String Fazar = response.getJSONArray("items").getJSONObject(0).get("fajr").toString();
String Zohr = response.getJSONArray("items").getJSONObject(0).get("dhuhr").toString();
String Asar = response.getJSONArray("items").getJSONObject(0).get("asr").toString();
String Magrib = response.getJSONArray("items").getJSONObject(0).get("maghrib").toString();
String Isha = response.getJSONArray("items").getJSONObject(0).get("isha").toString();
fazarId.setText(Fazar);
zoharid.setText(Zohr);
asarid.setText(Asar);
magribid.setText(Magrib);
ishaid.setText(Isha);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
});
}
You need to add your request object to the Volley queue (in your case, mQueue) in order for the request to be executed.
Example:
mQueue.add(request);
Internet permission is normal permission so the android system will not ask internet permission.
You just call this line:
mQueue.add(request);
end of the request.
Add below line after errorListener method at end of your request
mQueue.add("your request type");