String list - Android Studio

I'm using default LoginActivity and I don't know how to make few options in following code:
Code:
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("In this place exactly");
}
Someone knows what I supposed to do?

check the email string
---------- Post added at 08:02 PM ---------- Previous post was at 07:51 PM ----------
for(i=0;i<arrayemail.length();i++)
{
if(arrayemail(i).equals(email))
{
return // email id valid
boolean valid = true;
}
}
if(valid)
{
// email valid
}
else
{
//email id not valid
}

Related

Hook parcel readString, IBinder transact

Hello. I have this code.
Code:
public String getId() throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
String id;
try {
data.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
binder.transact(1, data, reply, 0);
reply.readException();
id = reply.readString();
} finally {
reply.recycle();
data.recycle();
}
return id;
}
How i can hook " id = reply.readString();" when a don't know method name like "getId()". Thanks.
PS: Sorry for my bad English.
Now i can hook "transact" method like this:
Code:
XposedHelpers.findAndHookMethod("android.os.BinderProxy", loadPackageParam.classLoader, "transact", int.class, Parcel.class, Parcel.class, int.class, new XC_MethodHook() {
protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
super.afterHookedMethod(param);
IBinder binder = (IBinder) param.thisObject;
String interfaceBinder = binder.getInterfaceDescriptor();
if (interfaceBinder.equals("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService")) {
// change result for readString
}
}
});
But i cant override "readString" result for Parcel (args[2]) object. How can i do this? Thanks.

[Q] writing txt file

I want to write a text file. But I am not sure how writing down works in Android. Here is my code:
Code:
EditText textbox1 = (EditText) findViewById(R.id.editText);
EditText textbox2 = (EditText) findViewById(R.id.editText2);
EditText textbox3 = (EditText) findViewById(R.id.editText3);
public void writeToPhonebook(View v) {
Button button=(Button) v;
try {
File fajl = new File("phonebook.txt");
Writer writer;
writer= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fajl, true), "UTF-8"));
writer.append(textbox1.getText() + "\t" + textbox2.getText() + "\t" + textbox3.getText());
writer.write("\r\n");
writer.close();
textbox1.setText("");
textbox2.setText("");
textbox3.setText("");
textbox1.requestFocus();
}
catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
can I just leave phonebook.txt or need to put something else? Because with this code apk can't even start on emulator.
OK I done this previus. I now need to load data from text file into table (table layout with 3 columns). Is it possible for application to determine number of needed rows without me adding certain number. Because that data will be changed.
You need permissions to write a file, you set them in the AndroidManifest xml (Every Android Studio project has their own manifest, set it in your project)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Then you need to open a file for input/output... You do this in whatever.java
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.util.Log;
public class FileOperations {
public FileOperations() {
}
public Boolean write(String fname, String fcontent){
try {
String fpath = "/sdcard/"+fname+".txt";
File file = new File(fpath);
// If file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fcontent);
bw.close();
Log.d("Suceess","Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String read(String fname){
BufferedReader br = null;
String response = null;
try {
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/"+fname+".txt";
br = new BufferedReader(new FileReader(fpath));
String line = "";
while ((line = br.readLine()) != null) {
output.append(line +"n");
}
response = output.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return response;
}
}
What is easier to display data from text file in: TableLayout or ViewList? If not sure total number of rows? Is there something for scrooling through it if can't fit the screen?
Scrollview
Grimspiller said:
What is easier to display data from text file in: TableLayout or ViewList? If not sure total number of rows? Is there something for scrooling through it if can't fit the screen?
Click to expand...
Click to collapse
1) Yes. Android provide scrollview to scroll on your query.
A. Horizontal scrollview
B. Vertical Scrollview.
Also you can you onTextwatcher() to check if the field size increase , onAfterTextchanged() method you can resize the box is.
private final TextWatcher passwordWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textView.setVisibility(View.VISIBLE);
}
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
textView.setVisibility(View.GONE);
} else{
textView.setText("You have entered : " + passwordEditText.getText());
}
}
};
I found this tutorial for multicolumn ListView on techlovejump.com ,but data for it is hardcoded. I am not sure is it suitable for dynamic data adding from text file.
Dynamic Data
Grimspiller said:
I found this tutorial for multicolumn ListView on techlovejump.com ,but data for it is hardcoded. I am not sure is it suitable for dynamic data adding from text file.
Click to expand...
Click to collapse
hey, As you see on after afterTextChanged(Editable s)
You can again call your table structure code to design it as per size.
I think you should try it once.
Share some amount of code if you find it difficult. I will help you afterTextChanged(Editable s).
I don't need to write text but to read it. Can you look at this code and tell me what is the problem? It can't find the file.
Code:
void showData(){
File fajl = new File("phonebook.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(fajl));
String line;
try {
while ((line = br.readLine()) != null) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
TextView im = new TextView(this);
im.setText(line);
im.setTextColor(Color.BLACK);
im.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
tr.addView(im);
tablel.addView(tr, new TableLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
button2.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
showData();
}
});
I have added to xml TableLayout and one row as header.
I use this for writing to text file:
Code:
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
try {
FileOutputStream fos = openFileOutput("phonebook.txt", Context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.append(textbox1.getText().toString() + "\t" + textbox2.getText().toString() + "\t" + textbox3.getText().toString());
osw.write("\r\n");
osw.close();
textbox1.setText("");
textbox2.setText("");
textbox3.setText("");
textbox1.requestFocus();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
});
Debbuger says it's writting file and lines just fine. But why I can't read it?
It creates "files" folder inside my app folder. And inside files it is phonebook.txt.

Thread crash on start itself

I am trying to create a thread in an android application to keep checking my firebase database to check if an otp value has been put in the child value of a node. But it keeps crashing as soon as I start the application. This is my code so far.
//Thread check otp
Thread t = new Thread() {
@override
public void run() {
while(!isInterrupted()) {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
@override
public void run() {
//check OTP if present on database
FirebaseDatabase.getInstance().getReference().child("Keys")
.addListenerForSingleValueEvent(new ValueEventListener() {
@override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Subjects keys = snapshot.getValue(Subjects.class);
//System.out.println(user.email);
Intent i = new Intent(getApplicationContext(), markAttendance.class);
i.putExtra("otp",keys.otpcode);
i.putExtra("subid", keys.subjectId);
finish();
startActivity(i);
}
}
@override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
Any help is much appreciated. Thnx in advance
To keep checking my firebase database to check if an otp value has been put
Click to expand...
Click to collapse
You don't need to create a background thread to do that, firebase listeners (and almost all operations, if not all of them) already run in a separated thread. You can safely register your ValueEventListener somewhere and let it there.
PS. You didn't post the logcat nor the structure of your database, so I can not help much about the crash.
pauljose97 said:
I am trying to create a thread in an android application to keep checking my firebase database to check if an otp value has been put in the child value of a node. But it keeps crashing as soon as I start the application. This is my code so far.
Code:
//Thread check otp
Thread t = new Thread() {
public void run() {
while(!isInterrupted()) {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
//check OTP if present on database
FirebaseDatabase.getInstance().getReference().child("Keys")
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Subjects keys = snapshot.getValue(Subjects.class);
//System.out.println(user.email);
Intent i = new Intent(getApplicationContext(), markAttendance.class);
i.putExtra("otp",keys.otpcode);
i.putExtra("subid", keys.subjectId);
finish();
startActivity(i);
}
}
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
Any help is much appreciated. Thnx in advance
Click to expand...
Click to collapse
Starting using adb logcat to see why your app is crashing. If I had to start a thread, I would create an async background task instead
Code:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
while(!isInterrupted()) {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
//check OTP if present on database
FirebaseDatabase.getInstance().getReference().child("Keys")
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Subjects keys = snapshot.getValue(Subjects.class);
//System.out.println(user.email);
Intent i = new Intent(getApplicationContext(), markAttendance.class);
i.putExtra("otp",keys.otpcode);
i.putExtra("subid", keys.subjectId);
finish();
startActivity(i);
}
}
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
};
task.execute();

WebApp + sql. Can't make sql to work.

Hey guys.
So, I've spent the last two days watching every tutorial about working with sqlite, but I'm doing something wrong and can't find out what.
The app is done, only needs the SQLite part, Its basicly a webapp with favorites.
Altough I have changed the code several times, this is what I ended up with:
DBManager.java
<code>
package com.rjpf.mywebapps;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager
{
private DbHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c)
{
context=c;
}
public DBManager open() throws SQLException
{
dbHelper = new DbHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
dbHelper.close();
}
public void insert(String name, String url)
{
ContentValues contentValue = new ContentValues();
contentValue.put(DbHelper.CONTACTS_COLUMN_NAME, name);
contentValue.put(DbHelper.CONTACTS_COLUMN_URL, url);
database.insert(dbHelper.CONTACTS_TABLE_NAME, null, contentValue);
}
}
</code>
When I try to call it in the main activity with:
MainActivity.java
<code>
(...)
private LinearLayout Layout_Add;
private TextView TxT_add_nomE;
private TextView TxT_add_urL;
private Button Button_Add_to_DB;
private Button btn_BACK_Add;
DbHelper myDB;
(...)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = new DbHelper(this);
(...)
Button_Add_to_DB.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
Add_ItemToDb();
}
});
(...)
public void Add_ItemToDb()
{
if (TxT_add_nomE.getText().toString().trim().length() == 0 || TxT_add_urL.getText().toString().trim().length() == 0)
{
TxT_add_nomE.setText("Please don't leave fields empty!");
return;
}
else
{
String addNome = TxT_add_nomE.getText().toString();
String addUrl = TxT_add_urL.getText().toString();
// ADD TO DB
DBManager DataManager = new DBManager(this);
DataManager.insert(addNome,addUrl); // This line is what gives the error, when I click the button to add the App craches
TxT_add_nomE.setText("Name");
TxT_add_urL.setText("Url");
}
}
</code>
Thanks in advance and sorry for the long post, This is my first app and also the first time in java

Download and parse xml file

Hello, I am learning to program in android and I have the following project. I need to download two XML files from the internet, these files correspond to fuel prices and the location of gas stations. The location and price come in different files, to join these files I need to identify the id of the service station and create a new file with the location and price of the fuel of each station. I am learning how to perform each of these steps. In the code that I add below I want to download a file, save it in memory and display it in TextView. The code does not work correctly, I manage to download the file but I cannot save it in memory to later show it in the Textview. The code downloads the data in the / data / folder, in order to verify that the connection is made and the data is downloaded. How can I download a file and save it in memory to later parse the XML?
Button button=(Button) findViewById(R.id.DownloadBt);
txt = (TextView) findViewById(R.id.txt);
button.setOnClickListener(this);
}
@override
public void onClick(View view){
switch (view.getId()){
case R.id.DownloadBt:
descargarPDF();
break;
}
}
void descargarPDF(){
String urlDescargarPlaces = "https://publicacionexterna.azurewebsites.net/publicaciones/places";
//String urlDescargarPrices = "https://publicacionexterna.azurewebsites.net/publicaciones/prices";
DescargarPDFAsyncTask descargarPlaces=new DescargarPDFAsyncTask("places.xml");
//DescargarPDFAsyncTask descargarPrices=new DescargarPDFAsyncTask("prices.xml");
descargarPlaces.execute(urlDescargarPlaces);
//descargarPrices.execute(urlDescargarPrices);
}
class DescargarPDFAsyncTask extends AsyncTask<String, Integer, String> {
String mFileName;
XMLParse xmlParse=new XMLParse();
DescargarPDFAsyncTask(String fileName){
mFileName=fileName;
}
@override
protected void onPreExecute(){
super.onPreExecute();
}
@override
protected String doInBackground(String... urlFichero) {
String urlADescargar=urlFichero[0];
HttpURLConnection conexion=null;
InputStream input=null;
OutputStream output=null;
try {
URL url = new URL(urlADescargar);
conexion = (HttpURLConnection) url.openConnection();
conexion.connect();
if(conexion.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Connection not successful";
}
input=conexion.getInputStream();
String rutaFicheroGuardado=getFilesDir()+ "/"+mFileName; // /data/data/com.exmaple.downloadurlfile/places.xml.
output=new FileOutputStream(rutaFicheroGuardado);
byte[] data=new byte[1024];
int count=0;
while((count=input.read(data)) >0){//!=-1;
output.write(data,0, count);
}
byteArrayStream = new ByteArrayInputStream(data);//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
} catch (MalformedURLException ex) {
ex.printStackTrace();
return "Error: "+ ex.getMessage();
} catch (IOException ex) {
ex.printStackTrace();
return "Error: "+ex.getMessage();
} finally{
{
try {
if(input!=null) input.close();
if(output!=null) output.close();
if(conexion!=null) conexion.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "Connection successful.";
}
@override
protected void onProgressUpdate(Integer...values){
super.onProgressUpdate(values);
}
@override
protected void onPostExecute(String mensaje){
super.onPostExecute(mensaje);
XMLParse xmlParse= new XMLParse();
xmlParse.parseXML();
Toast.makeText(getApplicationContext(),mensaje,Toast.LENGTH_LONG).show();
}
}
public class XMLParse {
StringBuilder result;
XMLParse(){
}
public void parseXML() {
XmlPullParserFactory parserFactory;
try {
parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserFactory.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(byteArrayStream,null);//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
processParsing(parser);
} catch (XmlPullParserException e) {
} catch (IOException e) {
}
}
private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
ArrayList<Player> players = new ArrayList<>();
int eventType = parser.getEventType();
Player currentPlayer = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
String eltName = null;
switch (eventType) {
case XmlPullParser.START_TAG:
eltName = parser.getName();
if ("place".equals(eltName)) {
currentPlayer = new Player();
players.add(currentPlayer);
} else if (currentPlayer != null) {
if ("name".equals(eltName)) {
currentPlayer.name = parser.nextText();
} else if ("cre_id".equals(eltName)) {
currentPlayer.cre_id = parser.nextText();
} else if ("x".equals(eltName)) {
currentPlayer.x = parser.nextText();
} else if("y".equals(eltName)){
currentPlayer.y = parser.nextText();
}
}
break;
}
eventType = parser.next();
}
printPlayers(players);
}
private void printPlayers(ArrayList<Player> players) {
StringBuilder builder = new StringBuilder();
for (Player player : players) {
builder.append(player.name).append("\n").
append(player.cre_id).append("\n").
append(player.x).append("\n").
append(player.y).append("\n\n");
}
txt.setText(builder.toString());
}
}
}

Categories

Resources