Hey I'm trying do application where i check my current location and save this location in ".txt" files. My application save this location in every "user set time" seconds. And it's work. Also I want add save files to Google drive. But I don't know how. Is there any method by which I can create a folder and save ".txt" files same as i did with local folder?
public class Save extends AppCompatActivity {
boolean sms = false;
int n_seconds, n_minutes, n_sum;
private String path = Environment.getExternalStorageDirectory().toString() + "/Loc/Save";
private Button buttonStartThread;
private Handler mainHandler = new Handler();
private volatile boolean stopThread = false;
NumberPicker edit_text_input_back, edit_text_input_back_2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_background);
buttonStartThread = findViewById(R.id.button_start_thread);
edit_phone_number = findViewById(R.id.edit_phone_number);
edit_mail = findViewById(R.id.edit_email);
edit_text_input_back = (NumberPicker) findViewById(R.id.edit_text_input_back);
edit_text_input_back.setMaxValue(60);
edit_text_input_back.setMinValue(0);
edit_text_input_back.setValue(0);
edit_text_input_back_2 = (NumberPicker) findViewById(R.id.edit_text_input_back_2);
edit_text_input_back_2.setMaxValue(60);
edit_text_input_back_2.setMinValue(0);
edit_text_input_back_2.setValue(0);
edit_text_input_back.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
n_seconds = i1;
}
});
edit_text_input_back_2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
n_minutes = 60 * i1;
}
});
}
public void startThread(View view) {
stopThread = false;
n_sum = n_seconds + n_minutes;
ExampleRunnable runnable = new ExampleRunnable(n_sum);
new Thread(runnable).start();
buttonStartThread.setEnabled(false);
}
public void stopThread(View view) {
stopThread = true;
buttonStartThread.setEnabled(true);
}
class ExampleRunnable implements Runnable {
int seconds;
ExampleRunnable(int seconds) {
this.seconds = seconds;
}
#Override
public void run() {
for (; ; ) {
for (int i = 0; i < seconds; i++) {
if (stopThread)
return;
if (i == n_sum-1) {
runOnUiThread(new Runnable() {
#Override
public void run() {
createDir();
createFile();
}
});
}
Log.d(TAG, "startThread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private void createDir() {
File folder = new File(path);
if(!folder.exists()){
try {
folder.mkdirs();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
private void createFile() {
File file = new File(path+"/"+System.currentTimeMillis()+".txt");
FileOutputStream fileOutputStream;
OutputStreamWriter outputStreamWriter;
try {
Intent intent = getIntent();
Double lat = intent.getDoubleExtra("adres", 0);
Double lon = intent.getDoubleExtra("adres2", 0);
String adr = intent.getStringExtra("adres3");
fileOutputStream = new FileOutputStream(file);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.append("Your adress: " + adr + ". " + "Your latitude: " + lat + ", " + "longtitude: " + lon+".");
outputStreamWriter.close();
fileOutputStream.close();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Thank you in advance
There are ample sources you can check for creating a folder, and uploading a file to Google Drive
Creating Folder
File fileMetadata = new File();
fileMetadata.setName("Invoices");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = driveService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Uploading File
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
For the specific mime type of a txt file, you might need to refer this StackOverflow post (text/plain). For specific Google applications mime types, please see documentation.
Please I need you to help me to find what I have been doing wrong. I have been having a problem while creating a file using android studio.
There is no error, but the file "textstring.txt" is not created.
W/System.err: java.io.IOException: open failed: ENOENT (No such file or directory) and
W/System.err: at java.io.File.createNewFile(File.java:944) are the warnings I become and it happens at myFile.createNewFile()
This is my code lines
private String INPUT_FILE = "textstring.txt";
private String inputString = "thisIsTheTextToWrite";
private File myFile = null;
private Button myWrite = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create a file
myFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Android/Data/" + getPackageName() + "/files/" + INPUT_FILE);
mWrite = (Button)findViewById(R.id.b_write);
mWrite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
FileOutputStream output = openFileOutput(INPUT_FILE, MODE_PRIVATE);
output.write(inputString.getBytes());
if(output != null)
output.close();
//
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
&& !Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState()))
{
myFile.createNewFile();
output = new FileOutputStream(myFile);
output.write(inputString.getBytes());
if(output != null)
output.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
}
The problem seems to occur at // myFile.createNewFile();
Why that ?
Thank you in advance
It is just a warning right ?
You should always check the result of myFile.createNewFile() :
if(!myFile.createNewFile()) {
Log.e("mDebug", "Couldn't create the file");
}
That's it
I'm trying to write a code I can write all the results values from accelerometer sensor into a .txt file. I can't write all the data in somehow. I think there is a problem in my loop. It is just reading about 10 to 15 samples.
How can I write all the values of the sensor into that file until I toggle off the button to stop? here is the code I wrote.
Thanks in advance!
public class MainActivity extends Activity implements SensorEventListener {
public SensorManager sm;
Sensor accelermeter;
private static final String DEBUG = "LogAccelermeter";
ToggleButton OnStore;
Button OffStore;
Button btnOn, btnOff;
TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
TextView sensorText;
// String for MAC address
private static String address;
private GestureDetectorCompat mDetector;
FileOutputStream fileOutputStream;
double TotalAccelerate;
ArrayList<Double> list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<Double>();
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
//for Accelermeter
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorText = (TextView) findViewById(R.id.sensor);
accelermeter = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelermeter, SensorManager.SENSOR_DELAY_NORMAL);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStorageDirectory();
File dir = new File(Root.getAbsolutePath() + "/MyApp");
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, "MyMessage.txt");
try {
fileOutputStream = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "SDcard not found", Toast.LENGTH_LONG).show();
}
OnStore = (ToggleButton) findViewById(R.id.onStore);
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
try {
for(double TotalAccelerate : list){
// System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
// fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}if (!OnStore.isChecked()){
try {
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
list.clear();
Collections.synchronizedList(list);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
String sensor1 = recDataString.substring(6, 10); //same again...
String sensor2 = recDataString.substring(11, 15);
String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V"); //update the textviews with sensor values
sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
}//end OnCreate Method
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + TotalAccelerate);
Log.i(DEBUG, "list values " + list);
}
//Find peak values.
public static ArrayList<Double> findPeaks(List<Double> points) {
ArrayList<Double> peaks = new ArrayList<Double>();
if (points == null || points.size() < 1)
return peaks;
Double x1_n_ref = 0.0;
int alpha = 0; //0=down, 1=up.
int size = points.size();// -1)/100;
for (int i = 0; i < size; i += 5) {
Double IndexValues = points.get(i);
if (IndexValues > 9) {
Double delta = (x1_n_ref - IndexValues);
if (delta < 0) {
x1_n_ref = IndexValues;
alpha = 1;
} else if (alpha == 1 && delta > 0) {
peaks.add(x1_n_ref);
alpha = 0;
}
} else if (alpha == 0) {
x1_n_ref = IndexValues;
}
}
return peaks;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onDown(MotionEvent event) {
Log.d(DEBUG_TAG, "onDown: " + event.toString());
Toast.makeText(getApplication(), "OnDown Touch Occur", Toast.LENGTH_LONG).show();
if (event.getX() > 0) {
mConnectedThread.write("1");
}
return true;
}
#Override
public void onLongPress(MotionEvent event) {
Log.d(DEBUG_TAG, "onLongPress: " + event.toString());
mConnectedThread.write("0");
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
#Override
public void onPause() {
super.onPause();
try {
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
Could you try this for the toggle button onClick callback? It should write all the data when it's unchecked.
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
// should do nothing
} else if (!OnStore.isChecked()){
try {
for(double TotalAccelerate : list){
//System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
To regulate the code to start/stop listen to the sensor event, add the following variable somewhere in this class:
private boolean isListening = false;
And make the following modifications to your existing code:
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
//
// set listening flag to true
//
isListening = true;
} else if (!OnStore.isChecked()){
//
// set listening flag to false
//
isListening = false;
try {
for(double TotalAccelerate : list){
//System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
//
// regulate
//
if (isListening) {
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + TotalAccelerate);
Log.i(DEBUG, "list values " + list);
}
}
I have a url "yyyyyyy.com/test.txt", which is a text file.
It contains urls of .mp3 audios.
yyyyyyy.de/1.mp3
yyyyyyy.de/2.mp3
yyyyyyy.de/3.mp3 //exactly like that
My intention was to read each line of this text file and store it in an array like
urls[0]=yyyyyyy.de/1.mp3
urls[1]=yyyyyyy.de/2.mp3 ...
this.
String[] urls;
int i=0;
Random rand;
int min=0;
int max=5; // I have 6 Urls in the text file
int randomNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rand = new Random();
randomNum = rand.nextInt((max - min) + 1) + min; //generates integer between 0-5
try {
// Create a URL for the desired page
URL url = new URL("yyyyy.de/test.txt"); //My text file location
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
urls[i]=str;
i++;
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
boolean isPLAYING = false;
if (!isPLAYING) {
isPLAYING = true;
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(urls[randomNum]);
mp.prepare();
mp.start();
} catch (IOException e) {
}
} else {
isPLAYING = false;
}
}
I have already add in Manifest.xml the android:permission.
I don't know where the problem is...the app closes itself and tells me
that this line " mp.setDataSource(urls[randomNum]);" is wrong
Here LogCat : http://textuploader.com/5iw5b
Thanks in advance !!
Your array is NULL
put this code after super.onCreate
urls=new String[max]
Update 3:
try this:
ArrayList<String> urls=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Create a URL for the desired page
URL url = new URL("yyyyy.de/test.txt"); //My text file location
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Log.i("test","url count="+urls.size());
boolean isPLAYING = false;
if (!isPLAYING) {
isPLAYING = true;
MediaPlayer mp = new MediaPlayer();
try {
int randomPos = new Random().nextInt(urls.size());
mp.setDataSource(urls.get(randomPos));
mp.prepare();
mp.start();
} catch (IOException e) {
}
} else {
isPLAYING = false;
}
}
I'm trying to figure out why my inputstream isn't working correctly. I am trying to connect to a server and get a JSON string and save it into the variable inputJSON. However inputJOSN is empty because my inputstream isn't working correctly. This line of code:
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
doesn't seem to be working properly and I'm not sure why?
public class AndroidClient extends ProfileActivity {
private TextView textIn;
public Thread rt;
public Socket socket = null;
public PrintWriter outputstrwr;
public OutputStream out = null;
public DataOutputStream dataOutputStream = null;
public DataInputStream dataInputStream = null;
public InputStream inputStr = null;
private final static String LOG_TAG = AndroidClient.class.getSimpleName();
private final Handler handler = new Handler();
private List<Profile> serviceInfoList = new ArrayList<Profile>();
// Map between list position and profile
private Map<Integer, Profile> posMap = new HashMap<Integer, Profile>();
private Map<String, Integer> addressMap = new HashMap<String, Integer>();
private static String profilePicBase64Str="";
private String inputJSON = "";
private String outputJSON = "";
private String outputJSONserv = "";
private Profile p;
//String urlInputStream = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e(LOG_TAG, "Before OnCreate() Try");
try {
Log.e(LOG_TAG, "In OnCreate() Try");
socket = new Socket("23.23.175.213", 9000); //Port 1337
Log.e(LOG_TAG, "Created Socket");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Log.e(LOG_TAG, "Created DataOutputStream");
dataInputStream = new DataInputStream(socket.getInputStream());
Log.e(LOG_TAG, "Created DataInputStream");
//out = new OutputStream();
out = socket.getOutputStream();
inputStr = socket.getInputStream();
//Thread readjsonthrd = new Thread(new ReadJSONThread());
//inputstrrd = new InputStreamReader(socket.getInputStream());
p = new Profile();
Log.e(LOG_TAG, "Created Profile Instance");
//Gets the local profile via JSON and converts into Profile type
Gson gson = new Gson();
Log.e(LOG_TAG, "Created Gson Instance" + "GetProfileJSONStr:" + p.getProfileJSONStr());
p = gson.fromJson(p.getProfileJSONStr(), Profile.class);
setProfile(p);
Log.e(LOG_TAG, "Converted Profile to JSON");
//Gson gson = new Gson();
Log.e(LOG_TAG, "Before: outputJSON = gson.toJson(p);");
outputJSON = gson.toJson(p).toString();
outputJSON = removeExcessStr(outputJSON);
Log.e(LOG_TAG, "ProfilePicStr Base64:"+p.getProfilePicStr());
outputJSON = outputJSON.replace("Name","name");
outputJSON = outputJSON.replace("TagLine","message");
outputJSON = outputJSON.replace("Title","title");
outputJSON = outputJSON.replace("Company", "company");
outputJSON = outputJSON.replace("Industry","industry");
outputJSON = outputJSON.replace("WhatIDo","whatido");
outputJSON = outputJSON.replace("WhoDoIWantToMeet","meetwho");
outputJSON = outputJSON.replace("WHOOZNEAR_PROFILEPIC","photo");
outputJSON = outputJSON.replaceAll("[c][o][n][t][e][n][t][:][/][/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+", getPicBase64Str()); /*"helloworld2"*/
if (!outputJSON.contains(",\"photo\":")) {
outputJSON = outputJSON.replace("}",",\"photo\":"+"\"IconnexUs\"}");
outputJSON = outputJSON.replace("}",",\"photo\":"+"\""+getPicBase64Str()+"\"}");
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"}");
}
else {
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"");
}
outputJSONserv = "{\"to\":\"broadcast\",\"type\":\"1\",\"payload\":"+outputJSON+"}";
Log.e(LOG_TAG, "Created outputJSON:" + outputJSON);
Log.e(LOG_TAG, "Created outputJSON Server:" + outputJSONserv);
JSONObject outObject = new JSONObject();
try {
outObject.put("photo", "hello");
outObject.put("type", "50");
outObject.put("payload", outputJSON);
outputJSON = gson.toJson(outObject).toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Value of PROFILEPIC STRING FROM PROFILEMAP: "+profileMap.get("WHOOZNEAR_PROFILEPIC"));
p.setProfilePicStr(ConvertandSetImagetoBase64(profileMap.get("WHOOZNEAR_PROFILEPIC")));
//String headerJSON = gson.toJson(outObject).toString();
outputJSON = outputJSON.substring(nthOccurrence(outputJSON, '{', 2)-1, nthOccurrence(outputJSON, '}', 1)-1);
String input = "["+"Ryan"+"[";
//"[foo".replaceAll(Pattern.quote("["), "\"");
String result = input.replaceAll(Pattern.quote("["), "\"");
Log.e(LOG_TAG, "REGEX REPLACEALL:"+result);
outputstrwr = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
outputstrwr.write(outputJSONserv);
Log.e(LOG_TAG, "Base64 String:"+p.getProfilePicStr());
Log.e(LOG_TAG, "Sent dataOutputStream");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Before initEventHandlers");
initEventHandlers();
Log.e(LOG_TAG, "After initEventHandlers");
//refreshViewModels();
Log.e(LOG_TAG, "Start Repeat Thread");
rt = new Thread(new RepeatingThread());
rt.start();
Log.e(LOG_TAG, "Started Repeat Thread");
}
#Override
public void onDestroy() {
super.onDestroy();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPause(){
super.onPause();
rt.stop();
}
#Override
public void onResume(){
super.onResume();
if (rt.isAlive() == false) {
//rt.start();
}
}
#Override
public void onStop(){
super.onStop();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String removeExcessStr(String json_excess) {
//String myString = myString.replace("=\"ppshein\"", "");
String json_excess1 = json_excess.replace("\"nameValues\":{", "");
String myString = json_excess1.replace(",\"profileId\":1,\"valid\":false}", "");
return myString;
}
public static String adddblquotattr(String attr) {
String result = attr.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static String adddblquotval(String val) {
String result = val.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static int nthOccurrence(String str, char c, int n) {
int pos = str.indexOf(c, 0);
while (n-- > 0 && pos != -1)
pos = str.indexOf(c, pos+1);
return pos;
}
public void setPicBase64Str(String profilePicBase64Str) {
this.profilePicBase64Str = profilePicBase64Str;
}
public String getPicBase64Str() {
return profilePicBase64Str;
}
public String ConvertandSetImagetoBase64(String imagePath) {
String base64 = null;
byte[] input = null;
try{
FileInputStream fd = new FileInputStream(imagePath);
Bitmap bmt = BitmapFactory.decodeFileDescriptor(fd.getFD());
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap tmp = ProfileActivity.scaleDownBitmap(bmt, 10, this);
tmp.compress(Bitmap.CompressFormat.JPEG, 10, stream);
input = stream.toByteArray();
base64 = Base64.encodeToString(input, Base64.DEFAULT);
//LocalProfileActivity.input = input;
}catch(Exception e){
Log.e(LOG_TAG,"[ONACTIVITYRESULT] Could not bind input to the bytearray: " + e.getMessage());
}
}
catch (Exception e){
Log.e("LocalProfile", "ConvertandSetImagetoBase64: Could not load selected profile image");
}
return base64;
}
public String getStringFromBuffer(InputStreamReader inputstrread){
BufferedReader bRead = new BufferedReader(inputstrread);
String line = null;
StringBuffer jsonText = new StringBuffer();
try {
while((line=bRead.readLine())!=null){
jsonText.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonText.toString();
}
public String ConvertByteArrayToString(byte[] b) {
// byte[] to string
String input = new String(b);
return input;
}
public byte[] ConvertStringToByteArray(String str) {
// string to byte[]
byte[] bytes = str.getBytes();
return bytes;
}
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely stream ");
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static String writeFile(Bitmap finalBitmap) {
String filePath = "";
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream outFile = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath = root+"/saved_images/"+fname;
return filePath;
}
public class RepeatingThread implements Runnable {
private final Handler mHandler = new Handler();
private int len = 0;
private byte[] input = new byte[len];
public RepeatingThread() {
//try {
Log.e(LOG_TAG, "Before inputJSON String");
//inputJSON = dataInputStream.readUTF();
//URL url = new URL("tcp://23.23.175.213:1337");
//inputJSON = dataInputStream.readUTF();
//inputstrrd = new InputStreamReader(socket.getInputStream());
String hello = "hello world";
//String inputJSON = getStringFromBuffer(new InputStreamReader(socket.getInputStream()));
//Convert
Log.e(LOG_TAG, "After inputJSON String:" + inputJSON);
/*}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//LOOK HERE FIRST
//inputJSON is what is received back from the server - Take the inputJSON
//String and use regular expressions HERE to remove all the other characters in the
//string except the payload JSON.
//refreshViewModels(inputJSON);
}
#Override
public void run() {
try {
//outputstrwr.write(outputJSONserv); //UNCOMMENT IF NEED TO SEND DATA TO GET JSON BACK
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "IN REPEATINGTHREAD-INPUTJSON:" + inputJSON);
refreshViewModels(inputJSON);
mHandler.postDelayed(this, 3000);
}
}
public void refreshViewModels(String inputJSON) {
try {
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
String[] from = new String[] { "profilePic", "neighborName",
"tagLine" };
int[] to = new int[] { R.id.avatar, R.id.username, R.id.email };
// prepare the list of all records
List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
List<Profile> profiles = new ArrayList<Profile>();
// Clear the position mapping list and reset it
this.posMap.clear();
Log.i(LOG_TAG, "NEW inputJSON: " + inputJSON);
inputJSON = getPayloadStr(inputJSON);
Log.i(LOG_TAG, "NEW inputJSON2: " + inputJSON);
JSONArray profileArray = new JSONArray(inputJSON);
for (int i=0; i<profileArray.length(); i++) {
JSONObject jsonObject = profileArray.getJSONObject(i);
Gson gson = new Gson();
Profile p = gson.fromJson(gson.toJson(jsonObject).toString(), Profile.class);
profiles.add(p);
}
int pos = 0;
// Creates the fillMaps list for the listAdapter
Log.i(LOG_TAG, "Profiles size: " + profiles.size());
//showToast("Profiles size: " + profiles.size());
for (Profile p : profiles) {
// Create mapping for list adapter
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("profilePic",
p.getAttributeValue("photo")== null? "Not Set" : p
.getAttributeValue("photo"));
map.put("neighborName",
p.getAttributeValue("Name") == null? "Not Set" : p
.getAttributeValue("Name"));
map.put("tagLine",
p.getAttributeValue("TagLine") == null? "Not Set" : p
.getAttributeValue("TagLine"));
fillMaps.add(map);
// Reset the postion mapping
this.posMap.put(pos++, p);
}
ListAdapter servicesListAdapter = new myAdapter(this, fillMaps,
R.layout.listitem, from, to);
servicesListView.setAdapter(servicesListAdapter);
} catch (Exception e) {
Log.e(LOG_TAG, "Error making list adapter: " + e.getMessage());
}
}
public String getPayloadStr(String profileString) {
Log.e("LOG_TAG", "Profile Str:"+profileString);
Pattern pattern = Pattern.compile(".*?payload\":(.*)\\}");
Log.e("LOG_TAG", "I got here 1");
Matcher matcher = pattern.matcher(profileString);
Log.e("LOG_TAG", "I got here 12");
//Matcher m = responseCodePattern.matcher(firstHeader);
matcher.matches();
matcher.groupCount();
//matcher.group(0);
Log.e("LOG_TAG", "I got here 2"+matcher.group(1));
return matcher.group(1);
}
private class myAdapter extends SimpleAdapter {
public myAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.listitem,
null);
}
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
((TextView) convertView.findViewById(R.id.username))
.setText((String) data.get("neighborName"));
((TextView) convertView.findViewById(R.id.email))
.setText((String) data.get("tagLine"));
// Convert a string representing an image back to an image
String base64 = ((String)data.get("profilePic"));
byte[] picBytes = Base64.decode(base64, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(picBytes, 0, picBytes.length);
//THE IF AND THE ELSE NEED TO BE SWITCHED
if (bitmap==null){
((ImageView) convertView.findViewById(R.id.avatar)).setImageResource(R.drawable.btn_whooznear);
}else{
((ImageView) convertView.findViewById(R.id.avatar)).setImageBitmap(bitmap);
}
return convertView;
}
}
public void callProfileActivity(int position)
{
// Catch the case when service info is empty
if(serviceInfoList.size()==0){
return;
}
Profile profClick = posMap.get(position);
String b64Str = profClick.getAttributeValue("photo");
Intent startViewActivity = new Intent();
startViewActivity.putExtra("TransProfile", (Profile)posMap.get(position));
startViewActivity.putExtra("PhotoBase64", b64Str);
if(serviceInfoList.size()>position){
//DO SOMETHING HERE
}else{
Log.e(LOG_TAG,"Profile doesn't exist in sevice infoList? Selecting first one");
}
startViewActivity.setClass(this, ViewProfileActivity.class);
startActivity(startViewActivity);
}
/**
* Initialize the event handlers
*/
public void initEventHandlers() {
// Service List View
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
servicesListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Profile clickedProfile = posMap.get(position);
//showToast("Clicked Pos: " + position);
/*Intent intent = new Intent(ConnectActivity.this, ViewProfileActivity.class);
intent.putExtra("ClickProfile", posMap.get(position));*/
callProfileActivity(position);
}
});
}
/*#Override
public void onBackPressed() { // do something on back.
super.onBackPressed();
Intent myIntent = new Intent(AndroidClient.this, ProfileActivity.class);
startActivity(myIntent);
return;
}*/
}
Your code is rather long, so I cannot be sure of what exactly is the problem, but there is definitely an issue here:
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
If you are calling this right after sending your URL request, the server may not have had time to send the result back, so is.available() may return zero or another value less than the actual number of bytes you would hope would be available. Try code like this for reading in the file.