Quiz error - Android Studio

Hello everyone! I have just made a program in Android Studio which should be a Quiz. If you could help me to find the mistake in my code I would be very grateful. Probably it's just a little mistake (as I am beginner...).
At the beginning I have created an arraylist, that does contain the strings a,b,c,d. Then, the program should make a few questions, that can be answered with Yes or No. If the user clicks the button yes, some strings are going to be removed from the Arraylist. This should happen until only one string is in the arraylist.
Here is my code:
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Arrays;
import java.util.Collections;
import java.util.*;
public class MainActivity extends AppCompatActivity {
static ArrayList<String> p = new ArrayList<String>();
static Button endbutton;
static Button questionbutton;
static Button yesbutton;
static Button nobutton;
static boolean yesbuttonisclicked=false;
static boolean nobuttonisclicked=false;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
endbutton = findViewById(R.id.endbutton);
questionbutton = findViewById(R.id.questionbutton);
yesbutton = findViewById(R.id.yesbutton);
nobutton = findViewById(R.id.nobutton);
p.add("a");
p.add("b");
p.add("c");
p.add("d");
yesbutton.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
yesbuttonisclicked=true;
nobuttonisclicked=false;
}
});
nobutton.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
nobuttonisclicked=true;
yesbuttonisclicked=false;
}
});
List array1 = Arrays.asList("1", "2", "3", "4");
Collections.shuffle(array1);
int i=0;
if (array1.get(i) == "1") {
questionbutton.setText("Question1");
if (yesbuttonisclicked) {
p.remove("a");
p.remove("b");
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
} else {
p.remove("c");
p.remove("d");
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
}
} else if (array1.get(i).equals("2")) {
questionbutton.setText("Question2");
if (yesbuttonisclicked) {
p.remove("a");
p.remove("c");
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
} else {
p.remove("b");
p.remove("d");
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
}
} else if (array1.get(i).equals("3")) {
questionbutton.setText("Question3");
if (yesbuttonisclicked) {
p.remove("a");
p.remove("d");
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
} else {
p.remove("c");
p.remove("b");
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
}
} else if (array1.get(i).equals("4")) {
questionbutton.setText("Question4");
if (yesbuttonisclicked) {
p.remove("d");
p.remove("c");
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
} else {
p.remove("a");
p.remove("b");
if (p.size() == 1) {
endbutton.setText(p.get(0));
}
}
}
}
}

Related

[Q] connect to bluetooth keyboard from android application problems

I wrote a simple application to connect to a bluetooth mini keyboard but am having trouble with the BluetoothDevice.connect() call.
it gives discovery service failed. I have no problem using the bluetooth pairing and connect from the bluetooth settings menu. The same code works with a bluesnap serial to bluetooth device.
Am I missing something obvious?
I'm on galaxy tab froyo.
The code is:
Code:
package test.com;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
//import test.com.connect.ClientConnectThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class connect extends Activity {
static final int ALERT_DIALOG_ID = 1;
private BtReceiver btReceiver;
private BluetoothAdapter btAdapter;
private final Handler handler = new Handler();
private static final UUID SIMPLE_BT_APP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ClientConnectThread clientConnectThread;
private BluetoothDataCommThread bluetoothDataCommThread;
private BluetoothDevice remoteDevice;
private BluetoothSocket activeBluetoothSocket;
private final String deviceAddress="98:9A:10:12:03:6E";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btAdapter=BluetoothAdapter.getDefaultAdapter();
if(btAdapter==null)
{
Toast.makeText(getApplicationContext(), "No Bluetooth Available",Toast.LENGTH_LONG ).show();
}else
{
if(!btAdapter.isEnabled())
{
Intent enableBtIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//REQUEST_ENABLE_BT is supposed to be 2 so
startActivityForResult(enableBtIntent, 2);
}
// we need a broadcast receiver now
btReceiver = new BtReceiver();
// register for state change broadcast events
IntentFilter stateChangedFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(btReceiver, stateChangedFilter);
// register for discovery events
IntentFilter actionFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(btReceiver, actionFoundFilter);
// check current state
int currentState = btAdapter.getState();
if (currentState == BluetoothAdapter.STATE_ON) {
findDevices();
}
}
}
public void findDevicesHandler(View view){
int currentState = btAdapter.getState();
if (currentState == BluetoothAdapter.STATE_ON) {
Toast.makeText(getApplicationContext(), "Finding devices",Toast.LENGTH_LONG ).show();
findDevices();
}
else
{
Toast.makeText(getApplicationContext(), "Adapter is off",Toast.LENGTH_LONG ).show();
}
}
protected void onActivityResult(int request,int result,Intent data)
{
if(result==RESULT_OK)
{
Toast.makeText(getApplicationContext(), "TURNING ON BLUETOOTH",Toast.LENGTH_LONG ).show();
}
}
public class BtReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
setStatus("Broadcast: Got ACTION_STATE_CHANGED");
int currentState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
if (currentState == BluetoothAdapter.STATE_ON) {
findDevices();
}
} else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
setStatus("Broadcast: Got ACTION_FOUND");
BluetoothDevice foundDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
setStatus("Device: " + foundDevice.getName() + "@" + foundDevice.getAddress());
remoteDevice=foundDevice;
if(remoteDevice.getAddress().equals(deviceAddress))
{
takeAction();
}
}
}
}
private void setStatus(String string){
Toast.makeText(getApplicationContext(), string,Toast.LENGTH_LONG ).show();
}
private void findDevices() {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedDevices) {
if (pairedDevice.getAddress().equals(deviceAddress)) {
setStatus("Found device: " + pairedDevice.getName() + "@" + deviceAddress);
remoteDevice = pairedDevice;
}
}
if (remoteDevice == null) {
setStatus("Starting discovery...");
if (btAdapter.startDiscovery()) {
setStatus("Discovery started...");
}
}
else
{
setStatus("Remote Device Address:"+remoteDevice.getAddress());
takeAction();
}
}
private void takeAction()
{
Toast.makeText(getApplicationContext(), "GETTING READY",Toast.LENGTH_LONG).show();
clientConnectThread = new ClientConnectThread(remoteDevice);
clientConnectThread.run();
}
@Override
protected void onDestroy() {
if (clientConnectThread != null) {
clientConnectThread.stopConnecting();
}
if (bluetoothDataCommThread != null) {
bluetoothDataCommThread.disconnect();
}
if (activeBluetoothSocket != null) {
try {
activeBluetoothSocket.close();
} catch (IOException e) {
//Log.e(DEBUG_TAG, "Failed to close socket", e);
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
btAdapter.cancelDiscovery();
this.unregisterReceiver(btReceiver);
super.onDestroy();
}
public void doStartDataCommThread() {
if (activeBluetoothSocket == null) {
setStatus("Can't start datacomm");
} else {
setStatus("Data comm thread starting");
bluetoothDataCommThread = new BluetoothDataCommThread(activeBluetoothSocket);
bluetoothDataCommThread.start();
}
}
private void setLastUsedRemoteBTDevice(String name) {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
Editor edit = prefs.edit();
edit.putString("LAST_REMOTE_DEVICE_ADDRESS", name);
edit.commit();
}
// client thread: used to make a synchronous connect call to a device
private class ClientConnectThread extends Thread {
private final BluetoothDevice remoteDevice;
private BluetoothSocket clientSocket;
public ClientConnectThread(BluetoothDevice remoteDevice) {
this.remoteDevice = remoteDevice;
clientSocket = null;
}
public void run() {
boolean success = false;
//success=true;
try {
btAdapter.cancelDiscovery();
//Method m = remoteDevice.getClass().getMethod("createRfcommSocket",new Class[] { int.class});
//Method m = remoteDevice.getClass().getMethod("createScoSocket",new Class[] { int.class});
//Method m = remoteDevice.getClass().getMethod("createInsecureRfcommSocket",new Class[] { int.class});
//clientSocket=(BluetoothSocket)m.invoke(remoteDevice,0);
clientSocket = remoteDevice.createRfcommSocketToServiceRecord(SIMPLE_BT_APP_UUID);
clientSocket.connect();
success = true;
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
try {
clientSocket.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(),"CLOSE:"+ e.toString(),Toast.LENGTH_LONG ).show();
}
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (NoSuchMethodException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} /*catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
}*/
final String status;
if (success) {
status = "Connected to remote device";
activeBluetoothSocket = clientSocket;
// we don't need to keep listening
//serverListenThread.stopListening();
} else {
status = "Failed to connect to remote device";
activeBluetoothSocket = null;
}
handler.post(new Runnable() {
public void run() {
setStatus(status);
setLastUsedRemoteBTDevice(remoteDevice.getAddress());
doStartDataCommThread();
}
});
}
public void stopConnecting() {
try {
clientSocket.close();
} catch (Exception e) {
//Log.e(DEBUG_TAG, "Failed to stop connecting", e);
Toast.makeText(getApplicationContext(), "CLOSE2:"+e.toString(),Toast.LENGTH_LONG ).show();
}
}
}
private class BluetoothDataCommThread extends Thread {
private final BluetoothSocket dataSocket;
private final InputStream inData;
public BluetoothDataCommThread(BluetoothSocket dataSocket) {
this.dataSocket = dataSocket;
InputStream inData = null;
try {
inData = dataSocket.getInputStream();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
this.inData = inData;
}
public void run() {
byte[] readBuffer = new byte[64];
int readSize = 0;
try {
while (true) {
readSize=inData.read(readBuffer, 0, 24);
final String inStr = new String(readBuffer, 0, readSize);
handler.post(new Runnable() {
public void run() {
doHandleReceivedCommand(inStr);
}
});
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
public void disconnect() {
try {
dataSocket.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
}
public void doHandleReceivedCommand(String rawCommand) {
String command = rawCommand.trim();
setStatus("Got: "+ command);
}
}
www.code.google.com
so it is right that not all bluetooth keyboard might work properly with any kind of android handheld....as yesterday i just read it in one of bluetooth keyboard

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();

My countdown timers don't work smooth.

Hello everyone i try to get commands from txt file and I want to run these commands in order for a certain period of time.I can get the commands from the txt file correctly but when I want to do these commands using a countdown timer for a certain period of time, there is a problem.The problem is that I do the first command in the time that I want, but it does not execute the next commands.
My txt file:
Ileri,5,1 /n -->this command work well.mp.start() method works for 5 seconds.Commands under this command do not work.
Sol,10,1 /n -->10 is operation time 1 is The number of repetitions.
Sag,5,1 /n
Geri,10,1 /n
Button's Code:
start_btn.setOnClickListener(new View.OnClickListener() { 
 @override
public void onClick(View v) {
String yon;
String saniye1;
String tekrar;
int i=0,j=0,c=0,d=0;
ArrayList<String> listS=new ArrayList<String>();
try {
Scanner s=new Scanner(new File("/data/data/com.example.emrecan.myapplication/files/komutlar.txt"));
while(s.hasNextLine())
{
listS.add(s.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] line2=new String[100];
for(String str:listS)
{
String[] line=str.split(",");
line2[c]=line;
line2[c+1]=line[i+1];
line2[c+2]=line[i+2];
c=c+3;
}
String [] line3=new String[c+2];
while(d<c)
{
line3[d]=line2[d];
d=d+1;
}
d=0;
tekrar=line3[2];
int tekrar1=Integer.parseInt(tekrar);
while(d<tekrar1)
{
while(j<=c-2)
{
yon = line3[j];
saniye1 = line3[j + 1];
sure1 = Long.parseLong(saniye1);
sure1=sure1*1000;
sure1=sure1+1000;
System.out.println(yon);
System.out.println(sure1);
System.out.println(tekrar1);
e=0;
switch (yon)
{
case "Ileri":
countdowntimer=new CountDownTimer(sure1,1000) {
@override
public void onTick(long millisUntilFinished) {
mp.start();
}
@override
public void onFinish() {
mp.stop();
Toast.makeText(getApplicationContext(),"İleri Komutu Bitti",Toast.LENGTH_LONG).show();
}
}.start();
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Sol":
countdowntimer2=new CountDownTimer(sure1,1000) {
@override
public void onTick(long millisUntilFinished) {
mp2.start();
}
@override
public void onFinish() {
mp2.stop();
Toast.makeText(getApplicationContext(),"Sol Komutu Bitti",Toast.LENGTH_LONG).show();
}
}.start();
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Sag":
countdowntimer3=new CountDownTimer(sure1,1000) {
@override
public void onTick(long millisUntilFinished) {
mp3.start();
}
@override
public void onFinish() {
mp3.stop();
Toast.makeText(getApplicationContext(),"Sag Komutu Bitti",Toast.LENGTH_LONG).show();
}
}.start();
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Geri":
countdowntimer4=new CountDownTimer(sure1,1000) {
@override
public void onTick(long millisUntilFinished) {
mp4.start();
}
@override
public void onFinish() {
mp4.stop();
Toast.makeText(getApplicationContext(),"Geri Komutu Bitti",Toast.LENGTH_LONG).show();
}
}.start();
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(), "Sıkıntı var!", Toast.LENGTH_LONG).show();
break;
}
j=j+3;
}
j=0;
d=d+1;
System.out.println('A');
}
}
});
App output:
I/System.out: Ileri
6000
1
I/System.out: Sol
11000
1
I/System.out: Sag
6000
1
I/System.out: Geri
11000
1
I/System.out: A
I solved my problem
I solved my problem by using thread.sleep(); and i'm writing here because someone might need my code.
start_btn.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
timer=new Timer();
///data/data/com.example.emrecan.myapplication/files/komutlar.txt
String yon;
String saniye1;
String tekrar;
int i=0,j=0,c=0,d=0;
ArrayList<String> listS=new ArrayList<String>();
try {
Scanner s=new Scanner(new File("/data/data/com.example.emrecan.myapplication/files/komutlar.txt"));
while(s.hasNextLine())
{
listS.add(s.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] line2=new String[100];
for(String str:listS)
{
String[] line=str.split(",");
line2[c]=line;
line2[c+1]=line[i+1];
line2[c+2]=line[i+2];
c=c+3;
}
String [] line3=new String[c+2];
while(d<c)
{
line3[d]=line2[d];
d=d+1;
}
d=0;
tekrar=line3[2];
int tekrar1=Integer.parseInt(tekrar);
while(d<tekrar1)
{
while(j<=c-2) {
yon = line3[j];
saniye1 = line3[j + 1];
sure1 = Long.parseLong(saniye1);
sure1 = sure1 * 1000;
//sure1 = sure1 + 1000;
System.out.println(yon);
System.out.println(sure1);
System.out.println(tekrar1);
e = 0;
while (sure1>0)
{
switch (yon) {
case "Ileri":
try {
outputStream.write(1);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Sol":
try {
outputStream.write(2);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Sag":
try {
outputStream.write(3);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Geri":
mp4.start();
try {
outputStream.write(4);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
default:
Toast.makeText(getApplicationContext(), "Sıkıntı var!", Toast.LENGTH_LONG).show();
break;
}
sure1=sure1-1000;
}
j=j+3;
}
j=0;
d=d+1;
System.out.println('A');
}
try {
outputStream.write(10);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});

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());
}
}
}

How can I parse an xml file from external folder in android studio?

Hi,
I have the following code but it doesn't work. When I work with the assets folder (InputStream is=getAssets().open("places.xml") I have no problem.
Thanks for help me.
public class MainActivity extends AppCompatActivity {
private TextView txt;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.txt);
parseXML();
Log.e("Mensaje:","onCreate");
}
private void parseXML() {
File file = null;
file = new File("/sdcard/Download/places.xml");
if(file.exists()){
Log.e("Message:", "File exists.");
}else {
Log.e("Message:", "File does NOT exists.");
}
try {
InputStream is = new FileInputStream(file);
XmlPullParserFactory parserFactory;
parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserFactory.newPullParser();
Log.e("Inside:","TRY");
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
processParsing(parser);
} catch (XmlPullParserException e) {
Log.e("Message:","Error1");
} catch (IOException e) {
Log.e("Message:","Error2");
}
}
private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException {
Log.e("Inside:","processParsing");
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();
Log.e("Inside:","printPlayers");
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