I have created this code but don't know why its not working. The code doesn't print all lines of the csvfile.
try{
File csvfile = new File(FullPath);
FileInputStream csvStream = new FileInputStream(csvfile);
BufferedReader in = new BufferedReader(new InputStreamReader(csvStream));
String line;
int iCount=0;
while ((line = in.readLine()) != null){
String[] RowData = line.split(",");
name[iCount] = RowData[0];
Toast.makeText(NewMessage.this, "CSV", 2000).show();
number[iCount] = RowData[1];
iCount++;
}
in.close();
Toast.makeText(NewMessage.this, "CSV Has uploaded", 2000).show();
}
catch(Exception e)
{
e.printStackTrace();
}
If the problem is that is not printing all lines of the file, you are overriding the array on loop. You should edit your question, because the array is working, the really problem is that the file wasn't printing all lines.
Here's the solution for name,number format:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Teste {
public static void main(String[] args) throws IOException {
Teste x = new Teste();
x.doTeste();
}
public void doTeste() throws IOException{
String fileName = "D:\\Projetos\\Testes\\src\\teste.txt";
BufferedReader in = null;
try{
File csvfile = new File(fileName);
FileInputStream csvStream = new FileInputStream(csvfile);
in = new BufferedReader(new InputStreamReader(csvStream));
String line;
String[] rowName = new String[(countLines(fileName)+1)];
String[] rowNameData = new String[(countLines(fileName)+1)];
int linha = 0;
while ((line = in.readLine()) != null){
String[] array = line.split(",");
rowName[linha] = array[0];
rowNameData[linha] = array[1];
++linha;
}
System.out.println("The rowName ARRAY");
for (String s: rowName){
System.out.println(s);
}
System.out.println("The rowNameData ARRAY");
for (String s: rowNameData){
System.out.println(s);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
in.close();
}
}
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
}
and for name in one line, and number the next line:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Teste {
public static void main(String[] args) throws IOException {
Teste x = new Teste();
x.doTeste();
}
public void doTeste() throws IOException{
String fileName = "D:\\Projetos\\Testes\\src\\teste.txt";
BufferedReader in = null;
try{
File csvfile = new File(fileName);
FileInputStream csvStream = new FileInputStream(csvfile);
in = new BufferedReader(new InputStreamReader(csvStream));
String line;
String[] rowName = new String[(countLines(fileName)+1)/2];
String[] rowNameData = new String[(countLines(fileName)+1)/2];
int iCount=0;
int x = 0;
int y = 0;
while ((line = in.readLine()) != null){
if (iCount == 0 || iCount%2 == 0) {
rowName[x] = line;
++x;
}
else {
rowNameData[y] = line;
++y;
}
iCount++;
}
System.out.println("The rowName ARRAY");
for (String s: rowName){
System.out.println(s);
}
System.out.println("The rowNameData ARRAY");
for (String s: rowNameData){
System.out.println(s);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
in.close();
}
}
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
}
Related
I tried every search on the net but couldn't managed to find a solution. I have managed to create a csv file(as attached in the image). But while importing it to sqlite whatever I do I can't have the correct rows in the correct positions in my sqlite, I believe it's about delimiters but couldn't find out can you help me please, I'm looking for it for the last 2 days. thank you
File exportDir = new File(Environment.getExternalStorageDirectory(), "/XXX/");
if (!exportDir.exists()) { exportDir.mkdirs(); }
File file2 = new File(exportDir, "XXX.csv");
FileReader file = new FileReader(file2);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues=new ContentValues();
String line = "";
String tableName =WordListOpenHelper.MY_LIST_TABLE;
db.beginTransaction();
while ((line = buffer.readLine()) != null)
{
x++;
String[] str = line.split("\\+");
if (x>5) {
contentValues.put(Contract.WordList.KEY_ENTRY, str[0]);
contentValues.put(Contract.WordList.KEY_NICKNAME_DATE, str[1]);
contentValues.put(Contract.WordList.KEY_LOCATION, str[2]);
contentValues.put(Contract.WordList.KEY_LOCATION_IMAGE, str[3]);
contentValues.put(Contract.WordList.KEY_HEART, str[4]);
db.insert(tableName, null, contentValues);
}
}
db.setTransactionSuccessful();
db.endTransaction();
And CSVWriter class
public class CSVWriter {
private PrintWriter pw;
private String separator;
private char escapechar;
private String lineEnd;
private char quotechar;
public static final String DEFAULT_SEPARATOR = "+\n";
public static final char NO_QUOTE_CHARACTER = '\u0000';
public static final char NO_ESCAPE_CHARACTER = '\u0000';
public static final String DEFAULT_LINE_END = "+\n";
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final char DEFAULT_ESCAPE_CHARACTER = ' ';
public CSVWriter(Writer writer) {
this(writer, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END);
}
public CSVWriter(Writer writer, String separator, char quotechar, char escapechar, String lineEnd) {
this.pw = new PrintWriter(writer);
this.separator = separator;
this.quotechar = quotechar;
this.escapechar = escapechar;
this.lineEnd = lineEnd;
}
public void writeNext(String[] nextLine) {
try{
if (nextLine == null)
return;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nextLine.length; i++) {
if (i != 0) {
sb.append(separator);
}
String nextElement = nextLine[i];
if (nextElement == null)
continue;
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
for (int j = 0; j < nextElement.length(); j++) {
char nextChar = nextElement.charAt(j);
if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
sb.append(escapechar).append(nextChar);
} else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
sb.append(escapechar).append(nextChar);
} else {
sb.append(nextChar);
}
}
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
}
sb.append(lineEnd);
pw.write(sb.toString());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void close() throws IOException {
pw.flush();
pw.close();
}
public void flush() throws IOException {
pw.flush();
}
}
CSV file in file manager:
This is not exactly a csv file, so it needs special dealing.
Use this method:
public String getLine(String line) {
line = line.trim();
if (line.isEmpty())
return "";
if (line.equals("\"\"+"))
return "";
if (line.length() <= 3)
return "";
return line.substring(1, line.length() - 1);
}
and this instead of your while loop:
boolean noMoreLines = false;
for (int i = 1; i <= 5; i++) {
line = buffer.readLine();
if (line == null) {
noMoreLines = true;
break;
}
}
if (!noMoreLines) {
while ((line = buffer.readLine()) != null) {
contentValues.put(Contract.WordList.KEY_ENTRY, getLine(line));
if ((line = buffer.readLine()) != null)
contentValues.put(Contract.WordList.KEY_NICKNAME_DATE, getLine(line));
if ((line = buffer.readLine()) != null)
contentValues.put(Contract.WordList.KEY_LOCATION, getLine(line));
if ((line = buffer.readLine()) != null)
contentValues.put(Contract.WordList.KEY_LOCATION_IMAGE, getLine(line));
if ((line = buffer.readLine()) != null)
contentValues.put(Contract.WordList.KEY_HEART, getLine(line));
db.insert(tableName, null, contentValues);
}
}
I need to store an array in shared prefs without the use of external libs like Prefser or Hawk. Which I tried and found a lot of problems with both of them.
So my search led me to two different methods:
Using Sets:
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
Using String manipulation:
//Set the values
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());
//Retrieve the values
String[] playlists = playlist.split(",");
The question: What would be a more efficient way to do it when the order of the items does not matter and I have a big amount of items (say > 300)?
The most efficient way would be store in a string via a ObjectSeializer.
A striing would loose the order of data but ObjectSerializer will remeber it. Here is a ObjectSerializer you can use:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectSerializer {
public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object deserialize(String str) throws IOException {
if (str == null || str.length() == 0) return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}
}
and call via:
sharedpref.putString("data",ObjectSerializer.serialize(array1));
JsonArray helps you to convert and store
public static void putStringArray(Context context, String key, String[] array) {
if (context == null) {
return;
}
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
JSONArray mJSONArray = new JSONArray(Arrays.asList(array));
editor.putString(key, String.valueOf(mJSONArray));
editor.apply();
}
public static String[] getStringArray(String key, Context context) {
if (context == null) {
return null;
}
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String[] stringArray = new String[0];
try {
JSONArray jsonArray = new JSONArray(prefs.getString(key, ""));
int len = jsonArray.length();
stringArray = new String[len];
for (int i = 0; i < len; i++) {
try {
stringArray[i] = jsonArray.getString(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return stringArray;
}
I am uploading image to server but image is rotate after uploaded to server Even preview is showing correct.
So many people facing this problem i found this link but didn't work. And there is many solution but i am not figure out how to fit in my code.
Please help me.
Here is my code
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fonts.Text.MyTextView;
import com.generalClass.files.UploadFile;
import com.hwindiapp.driver.db.sqLite.DBConnect;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
public class AddVehicleDocActivity extends AppCompatActivity {
private static final int FILE_SELECT_CODE = 124;
private Toolbar mToolbar;
TextView text_header;
MyTextView insuranceHTxt;
MyTextView permitHTxt;
MyTextView vRegHTxt;
MyTextView insNotFoundTxt;
MyTextView permitNotFoundTxt;
MyTextView vRegNotFoundTxt;
DBConnect dbConnect;
Button insBtn;
Button permitBtn;
Button vRegBtn;
LinearLayout insImgVIew;
LinearLayout permitImgVIew;
LinearLayout vRegImgVIew;
String language_labels_get_frm_sqLite = "";
String LBL_DOCUMENTS_TXT_str = "";
String LBL_YOUR_INSURANCE_TXT_str = "";
String LBL_WRONG_FILE_SELECTED_TXT_str = "";
String LBL_LOADING_TXT_str = "";
String LBL_YOUR_PERMIT_TXT_str = "";
String LBL_VEHICLE_REG_TXT_str = "";
String LBL_NOT_FOUND_TXT_str = "";
String LBL_BTN_OK_TXT_str = "";
String LBL_ERROR_TXT_str = "";
String LBL_TRY_AGAIN_LATER_TXT_str = "";
String LBL_DOC_UPLOAD_SUCCESS_TXT_str = "";
String LBL_ADD_TXT_str = "";
String LBL_EDIT_TXT_str = "";
String LBL_SUCCESS_TXT_str = "";
String LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = "";
String LBL_NOTE_UPLOAD_DOC_TXT_str = "";
String LBL_CANCEL_TXT_str = "";
String currentDocType = "";
String carJson_str = "";
String vIns = "";
String vPermit = "";
String vReg = "";
android.support.v7.app.AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_vehicle_doc);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
dbConnect = new DBConnect(this, "UC_Partner_Labels.db");
text_header = (TextView) findViewById(R.id.text_header);
insuranceHTxt = (MyTextView) findViewById(R.id.insuranceHTxt);
permitHTxt = (MyTextView) findViewById(R.id.permitHTxt);
vRegHTxt = (MyTextView) findViewById(R.id.vRegHTxt);
insNotFoundTxt = (MyTextView) findViewById(R.id.insNotFoundTxt);
permitNotFoundTxt = (MyTextView) findViewById(R.id.permitNotFoundTxt);
vRegNotFoundTxt = (MyTextView) findViewById(R.id.vRegNotFoundTxt);
insImgVIew = (LinearLayout) findViewById(R.id.insImgArea);
permitImgVIew = (LinearLayout) findViewById(R.id.permitImgArea);
vRegImgVIew = (LinearLayout) findViewById(R.id.vRegImgArea);
insBtn = (Button) findViewById(R.id.insBtn);
permitBtn = (Button) findViewById(R.id.permitBtn);
vRegBtn = (Button) findViewById(R.id.vRegBtn);
insBtn.setOnClickListener(new setOnClickAct());
permitBtn.setOnClickListener(new setOnClickAct());
vRegBtn.setOnClickListener(new setOnClickAct());
insImgVIew.setOnClickListener(new setOnClickAct());
permitImgVIew.setOnClickListener(new setOnClickAct());
vRegImgVIew.setOnClickListener(new setOnClickAct());
carJson_str = getIntent().getStringExtra("CarJson");
/* Set Labels */
getLanguageLabelsFrmSqLite();
/* Set Labels Finished */
ImageView back_navigation = (ImageView) findViewById(R.id.back_navigation);
back_navigation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AddVehicleDocActivity.super.onBackPressed();
}
});
Log.d("carJson_str", ":" + carJson_str);
try {
parseCarJson(carJson_str);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLanguageLabelsFrmSqLite() {
Cursor cursor = dbConnect.execQuery("select vValue from labels WHERE vLabel=\"Language_labels\"");
cursor.moveToPosition(0);
language_labels_get_frm_sqLite = cursor.getString(0);
JSONObject obj_language_labels = null;
try {
obj_language_labels = new JSONObject(language_labels_get_frm_sqLite);
LBL_DOCUMENTS_TXT_str = obj_language_labels.getString("LBL_DOCUMENTS_TXT");
LBL_YOUR_INSURANCE_TXT_str = obj_language_labels.getString("LBL_YOUR_INSURANCE_TXT");
LBL_WRONG_FILE_SELECTED_TXT_str = obj_language_labels.getString("LBL_WRONG_FILE_SELECTED_TXT");
LBL_LOADING_TXT_str = obj_language_labels.getString("LBL_LOADING_TXT");
LBL_YOUR_PERMIT_TXT_str = obj_language_labels.getString("LBL_YOUR_PERMIT_TXT");
LBL_VEHICLE_REG_TXT_str = obj_language_labels.getString("LBL_VEHICLE_REG_TXT");
LBL_NOT_FOUND_TXT_str = obj_language_labels.getString("LBL_NOT_FOUND_TXT");
LBL_BTN_OK_TXT_str = obj_language_labels.getString("LBL_BTN_OK_TXT");
LBL_ERROR_TXT_str = obj_language_labels.getString("LBL_ERROR_TXT");
LBL_TRY_AGAIN_LATER_TXT_str = obj_language_labels.getString("LBL_TRY_AGAIN_LATER_TXT");
LBL_DOC_UPLOAD_SUCCESS_TXT_str = obj_language_labels.getString("LBL_DOC_UPLOAD_SUCCESS_TXT");
LBL_ADD_TXT_str = obj_language_labels.getString("LBL_ADD_TXT");
LBL_EDIT_TXT_str = obj_language_labels.getString("LBL_EDIT_TXT");
LBL_SUCCESS_TXT_str = obj_language_labels.getString("LBL_SUCCESS_TXT");
LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = obj_language_labels.getString("LBL_BTN_TRIP_CANCEL_CONFIRM_TXT");
LBL_NOTE_UPLOAD_DOC_TXT_str = obj_language_labels.getString("LBL_NOTE_UPLOAD_DOC_TXT");
LBL_CANCEL_TXT_str = obj_language_labels.getString("LBL_CANCEL_TXT");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (obj_language_labels != null) {
text_header.setText("" + LBL_DOCUMENTS_TXT_str);
insuranceHTxt.setText("" + LBL_YOUR_INSURANCE_TXT_str);
permitHTxt.setText("" + LBL_YOUR_PERMIT_TXT_str);
vRegHTxt.setText("" + LBL_VEHICLE_REG_TXT_str);
insNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
permitNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
vRegNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
insBtn.setText(LBL_ADD_TXT_str);
permitBtn.setText(LBL_ADD_TXT_str);
vRegBtn.setText(LBL_ADD_TXT_str);
}
}
public void parseCarJson(String carJson) throws JSONException {
JSONObject obj_profile = new JSONObject(carJson);
vIns = obj_profile.getString("vInsurance");
vPermit = obj_profile.getString("vPermit");
vReg = obj_profile.getString("vRegisteration");
if (vIns == null || vIns.equals("")) {
insNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(0);
}
if (vPermit == null || vPermit.equals("")) {
permitNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(1);
}
if (vReg == null || vReg.equals("")) {
vRegNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(2);
}
}
public void setDocView(int id) {
if (id == 0) {
insNotFoundTxt.setVisibility(View.GONE);
insBtn.setText(LBL_EDIT_TXT_str);
insImgVIew.setVisibility(View.VISIBLE);
} else if (id == 1) {
permitNotFoundTxt.setVisibility(View.GONE);
permitBtn.setText(LBL_EDIT_TXT_str);
permitImgVIew.setVisibility(View.VISIBLE);
} else if (id == 2) {
vRegNotFoundTxt.setVisibility(View.GONE);
vRegBtn.setText(LBL_EDIT_TXT_str);
vRegImgVIew.setVisibility(View.VISIBLE);
}
}
public class setOnClickAct implements View.OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.insBtn:
currentDocType = "vInsurance";
chooseFIle();
break;
case R.id.permitBtn:
currentDocType = "vPermit";
chooseFIle();
break;
case R.id.vRegBtn:
currentDocType = "vRegisteration";
chooseFIle();
break;
case R.id.insImgArea:
openDocument(vIns);
break;
case R.id.permitImgArea:
openDocument(vPermit);
break;
case R.id.vRegImgArea:
openDocument(vReg);
break;
}
}
}
public void openDocument(String documentName) {
Log.d("Open doc","::"+CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName));
startActivity(browserIntent);
}
public void chooseFIle() {
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, FILE_SELECT_CODE);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == FILE_SELECT_CODE) {
Uri uri = data.getData();
// Log.d("Path", "::" + uri.getPath());
// Log.d("Path", "::" + getPath(uri));
String filePath = "";
filePath = (getPath(uri) == null) ? uri.getPath() : getPath(uri);
// Log.d("Ext", ":" + getFileExt(filePath));
final ArrayList<String[]> paramsList = new ArrayList<>();
paramsList.add(generateImageParams("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId")));
paramsList.add(generateImageParams("type", "UploadVehicleDoc"));
paramsList.add(generateImageParams("iDriverId", getIntent().getStringExtra("UserID")));
paramsList.add(generateImageParams("DocUploadType", currentDocType));
if (getFileExt(filePath).equalsIgnoreCase("jpg") || getFileExt(filePath).equalsIgnoreCase("gif") || getFileExt(filePath).equalsIgnoreCase("png")
|| getFileExt(filePath).equalsIgnoreCase("jpeg") || getFileExt(filePath).equalsIgnoreCase("bmp") || getFileExt(filePath).equalsIgnoreCase("pdf")
|| getFileExt(filePath).equalsIgnoreCase("doc") || getFileExt(filePath).equalsIgnoreCase("docx")) {
File selectedFile = new File(filePath);
if (selectedFile != null) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str);
final String finalFilePath = filePath;
alertDialogBuilder
.setMessage(selectedFile.getName() + "\n" + LBL_NOTE_UPLOAD_DOC_TXT_str)
.setCancelable(true)
.setNegativeButton(LBL_CANCEL_TXT_str, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog.dismiss();
}
})
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
new uploadDocument(finalFilePath, currentDocType + "." + getFileExt(finalFilePath), paramsList).execute();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
// showErrorOnSelection();
showMessage(LBL_ERROR_TXT_str, LBL_WRONG_FILE_SELECTED_TXT_str);
}
}
}
}
public String[] generateImageParams(String key, String content) {
String[] tempArr = new String[2];
tempArr[0] = key;
tempArr[1] = content;
return tempArr;
}
public class uploadDocument extends AsyncTask<String, String, String> {
String selectedPath;
String responseString = "";
ProgressDialog myPDialog;
String temp_File_Name = "";
ArrayList<String[]> paramsList;
public uploadDocument(String selectedPath, String temp_File_Name, ArrayList<String[]> paramsList) {
this.selectedPath = selectedPath;
this.temp_File_Name = temp_File_Name;
this.paramsList = paramsList;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
myPDialog = new ProgressDialog(AddVehicleDocActivity.this, R.style.DialogTheme_custom);
myPDialog.setMessage("" + LBL_LOADING_TXT_str);
myPDialog.setCancelable(false);
myPDialog.setCanceledOnTouchOutside(false);
myPDialog.show();
}
#Override
protected String doInBackground(String... strings) {
responseString = new UploadFile().uploadImageAsFile(selectedPath, temp_File_Name, "vFile", paramsList);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
myPDialog.dismiss();
Log.d("responseString", "::" + responseString);
if (responseString != null && !responseString.equals("")) {
try {
JSONObject obj_temp = new JSONObject(responseString);
String action_str = obj_temp.getString("Action");
String fileName_str = obj_temp.getString("vFileName");
if (action_str.equals("1")) {
showMessage(LBL_SUCCESS_TXT_str, LBL_DOC_UPLOAD_SUCCESS_TXT_str);
JSONObject obj_CarJson = new JSONObject(carJson_str);
if (currentDocType.equals("vInsurance")) {
obj_CarJson.remove("vInsurance");
obj_CarJson.put("vInsurance", fileName_str);
vIns = fileName_str;
setDocView(0);
} else if (currentDocType.equals("vPermit")) {
obj_CarJson.remove("vPermit");
obj_CarJson.put("vPermit", fileName_str);
vPermit = fileName_str;
setDocView(1);
} else if (currentDocType.equals("vRegisteration")) {
obj_CarJson.remove("vRegisteration");
obj_CarJson.put("vRegisteration", fileName_str);
vReg = fileName_str;
setDocView(2);
}
obj_CarJson.remove("eStatus");
obj_CarJson.put("eStatus", "Inactive");
carJson_str = obj_CarJson.toString();
Intent setData = new Intent();
setData.putExtra("CarJson", carJson_str);
setData.putExtra("DriverProfileData", obj_temp.getString("DriverProfileData").toString());
setData.putExtra("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId"));
setResult(RESULT_OK, setData);
// Driver_main_profile.updated_json_responseString_profile = obj_profileJson.toString();
//
// Driver_main_profile.driverDocUpdated = true;
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} catch (JSONException e) {
e.printStackTrace();
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
}
}
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
public String getPath(Uri uri) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
} else {
return null;
}
}
public void showMessage(String title_str, String content_str) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(title_str);
alertDialogBuilder
.setMessage(content_str)
.setCancelable(true)
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
Here is my Upload code
public class UploadFile {
public String uploadImageAsFile(String sourceFileUri, String fileName, String imageParamKey, ArrayList<String[]> params) {
ExifInterface exif = null; //Since API Level 5
try {
exif = new ExifInterface(sourceFileUri);
} catch (IOException e) {
e.printStackTrace();
}
String exifImage = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
String responseString = "";
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(exifImage));
byte[] data;
try {
data = convertToByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(CommonUtilities.SERVER_URL);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity(/*HttpMultipartMode.BROWSER_COMPATIBLE,"9999999999", Charset.defaultCharset()*/);
for (int i = 0; i < params.size(); i++) {
String[] paramsArr = params.get(i);
multipartEntity.addPart(paramsArr[0], new StringBody(paramsArr[1]));
}
ContentBody cbFile = new FileBody(new File(exifImage)/*, "multipart/form-data"*/);
multipartEntity.addPart(imageParamKey, cbFile);
httpPost.setEntity(multipartEntity);
// httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
// httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
// httpPost.setHeader("Content-Type", "multipart/form-data");
// httpPost.setHeader("Content-Type", "image/png");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setRequestProperty("ENCTYPE", "multipart/form-data");
// httpPost.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// httpPost.addHeader("Content-Type", "multipart/form-data;charset=UTF-8;boundary=654654");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setHeader("ENCTYPE", "multipart/form-data");
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if (httpResponse != null) {
Log.d("success", "success:" + httpResponse.toString());
responseString = EntityUtils.toString(httpResponse.getEntity());
} else { // Error, no response.
Log.d("Failed", "failed:" + httpResponse.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return responseString;
}
private byte[] convertToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = inputStream.read();
while (next > -1) {
bos.write(next);
next = inputStream.read();
}
bos.flush();
return bos.toByteArray();
}
/**
* #param encodedString
* #return bitmap (from given string)
*/
public Bitmap StringToBitMap(String encodedString){
try{
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
}
You shouldn't rotate the image after upload. You need to rotate it before. The preview is correct maybe because you're respecting Exif values when showing it. But the server isn't.
You need to rotate the image according to it's exif rotation:
https://stackoverflow.com/a/20480741/3410697
And only then you should upload it to the server
Call this function where you get path of image
public void setImage(String _path) {
int orientation = CustomImageUtil.getExifOrientation(_path);
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, resample);
if (orientation == 90) {
bitmap = CustomImageUtil.rotate(bitmap, 90);
} else if (orientation == 180) {
bitmap = CustomImageUtil.rotate(bitmap, 180);
} else if (orientation == 270) {
bitmap = CustomImageUtil.rotate(bitmap, 270);
}
// use your bitmap here
}
CustomImageUtil.class:
public class CustomImageUtil {
public static String getRealPathFromURI(Context context,Uri contentURI) {
String result;
Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 60, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
/**
* getExifOrientation -- Roate the image on the right angel
* #param filepath -- path of the file to be rotated
* #return
*/
public static int getExifOrientation(String filepath) {
int degree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException ex) {ex.printStackTrace();
}
if (exif != null) {
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
// We only recognize a subset of orientation tag values.
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
}
}
return degree;
}
// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees, (float) b.getWidth() / 2,
(float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {ex.printStackTrace();
}
}
return b;
}
}
To convert Bitmap to Uri
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
I am getting JSON data from a web service and would like to display a progress bar while the data is downloading. All the examples I have seen use a StringBuilder like so:
//Set up the initial connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.connect();
InputStream stream = connection.getInputStream();
//read the result from the server
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line + '\n');
}
result = builder.toString();
I got the ProgressBar to work by downloading the data as a byte array, then converting the byte array to a String, but I'm wondering if there is a 'more correct' way to do this. Since I've found no other way of doing this, the following class can also serve as a working example, seems a bit of a hack, but it does work well.
package com.royaldigit.newsreader.services;
import android.os.AsyncTask;
import android.util.Log;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.royaldigit.newsreader.controller.commands.CommandInterface;
import com.royaldigit.newsreader.model.data.SearchResultDO;
import com.royaldigit.newsreader.model.data.SearchTermDO;
/**
* Gets news results from Feedzilla based on the search term currently stored in model.searchTermDO
*
* Sends progress update and returns results to the CommandInterface command reference:
* * command.onProgressUpdate(progress);
* * command.serviceComplete(results);
*
*
*/
public class FeedzillaSearchService {
private static final String TAG = "FeedzillaSearchService";
private static final String SERVICE_URI = "http://api.feedzilla.com/v1/categories/26/articles/search.json?q=";
private static final int STREAM_DIVISIONS = 10;
private CommandInterface command;
private SearchTermDO currentSearchTermDO;
private Integer maximumResults;
private DownloadTask task;
private ArrayList<SearchResultDO> results;
public Boolean isCanceled = false;
public void getData(CommandInterface cmd, SearchTermDO termDO, Integer maxResults){
command = cmd;
currentSearchTermDO = termDO;
//Feedzilla only allows count to be 100 or less, anything over throws an error
maximumResults = (maxResults > 100)? 100 : maxResults;
results = new ArrayList<SearchResultDO>();
task = new DownloadTask();
task.execute();
}
public void cancel() {
isCanceled = true;
if(task != null) task.cancel(true);
}
/**
* Handle GET request
*
*/
private class DownloadTask extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void...voids) {
String result = "";
if(currentSearchTermDO == null || currentSearchTermDO.term.equals("")) return result;
BufferedReader reader = null;
publishProgress(0);
try {
String path = SERVICE_URI + URLEncoder.encode(currentSearchTermDO.term, "UTF-8") + "&count=" + maximumResults;
Log.d(TAG, "path = "+path);
URL url = new URL(path);
//Set up the initial connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.connect();
int length = connection.getContentLength();
InputStream stream = connection.getInputStream();
byte[] data = new byte[length];
int bufferSize = (int) Math.ceil(length / STREAM_DIVISIONS);
int progress = 0;
for(int i = 1; i < STREAM_DIVISIONS; i++){
int read = stream.read(data, progress, bufferSize);
progress += read;
publishProgress(i);
}
stream.read(data, progress, length - progress);
publishProgress(STREAM_DIVISIONS);
result = new String(data);
} catch (Exception e) {
Log.e(TAG, "Exception "+e.toString());
} finally {
if(reader != null){
try {
reader.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
int currentProgress = progress[0] * 100/STREAM_DIVISIONS;
if(!this.isCancelled()) command.onProgressUpdate(currentProgress);
}
#Override
protected void onPostExecute(String result){
if(!this.isCancelled()) downloadTaskComplete(result);
}
}
/**
*
* #param data
*/
private void downloadTaskComplete(Object data){
if(!isCanceled){
try {
Log.d(TAG, data.toString());
JSONObject obj = new JSONObject(data.toString());
JSONArray array = obj.getJSONArray("articles");
for(int i = 0; i < array.length(); i++){
SearchResultDO dataObj = new SearchResultDO();
dataObj.title = array.getJSONObject(i).getString("title");
dataObj.url = array.getJSONObject(i).getString("url");
dataObj.snippet = array.getJSONObject(i).getString("summary");
dataObj.source = array.getJSONObject(i).getString("source");
dataObj.date = array.getJSONObject(i).getString("publish_date");
dataObj.termId = currentSearchTermDO.id;
//Reformat date
SimpleDateFormat format1 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
try {
Date date = format1.parse(dataObj.date);
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dataObj.date = format2.format(date);
} catch(ParseException pe) {
Log.e(TAG, pe.getMessage());
}
results.add(dataObj);
}
command.serviceComplete(results);
} catch(JSONException e){
Log.e(TAG, e.toString());
command.serviceComplete(results);
}
}
}
}
UPDATE: Here is the finished version of the class using the suggestions from Nikolay. I ended up using the StringBuilder after all. The previous version would break because some times connection.getContentLength() returns -1. This version degrades gracefully for that case. Tested this implementation quite a bit and it seems bulletproof.
package com.royaldigit.newsreader.services;
import android.os.AsyncTask;
import android.util.Log;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.royaldigit.newsreader.controller.commands.CommandInterface;
import com.royaldigit.newsreader.model.data.SearchResultDO;
import com.royaldigit.newsreader.model.data.SearchTermDO;
/**
* Gets news results from Feedzilla based on the search term currently stored in model.searchTermDO
*
* Sends progress update and returns results to the CommandInterface command reference:
* * command.onProgressUpdate(progress);
* * command.serviceComplete(results);
*
*/
public class FeedzillaSearchService implements SearchServiceInterface {
private static final String TAG = "FeedzillaSearchService";
private static final String SERVICE_URI = "http://api.feedzilla.com/v1/categories/26/articles/search.json?q=";
private CommandInterface command;
private SearchTermDO currentSearchTermDO;
private Integer maximumResults;
private DownloadTask task;
private ArrayList<SearchResultDO> results;
private Boolean isCanceled = false;
public void getData(CommandInterface cmd, SearchTermDO termDO, Integer maxResults){
command = cmd;
currentSearchTermDO = termDO;
//Feedzilla only allows count to be 100 or less, anything over throws an error
maximumResults = (maxResults > 100)? 100 : maxResults;
results = new ArrayList<SearchResultDO>();
task = new DownloadTask();
task.execute();
}
public void cancel() {
isCanceled = true;
if(task != null) task.cancel(true);
}
/**
* Handle GET request
*
*/
private class DownloadTask extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void...voids) {
String result = "";
if(currentSearchTermDO == null || currentSearchTermDO.term.equals("")) return result;
BufferedReader reader = null;
publishProgress(0);
try {
String path = SERVICE_URI + URLEncoder.encode(currentSearchTermDO.term, "UTF-8") + "&count=" + maximumResults;
Log.d(TAG, "path = "+path);
URL url = new URL(path);
//Set up the initial connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(20000);
connection.connect();
//connection.getContentType() should return something like "application/json; charset=utf-8"
String[] values = connection.getContentType().toString().split(";");
String charset = "";
for (String value : values) {
value = value.trim();
if (value.toLowerCase().startsWith("charset=")) {
charset = value.substring("charset=".length());
break;
}
}
//Set default value if charset not set
if(charset.equals("")) charset = "utf-8";
int contentLength = connection.getContentLength();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
/**
* connection.getContentLength() can return -1 on some connections.
* If we have the content length calculate progress, else just set progress to 100 and build the string all at once.
*
*/
if(contentLength>-1){
//Odd byte array sizes don't always work, tried 512, 1024, 2048; 1024 is the magic number because it seems to work best.
byte[] data = new byte[1024];
int totalRead = 0;
int bytesRead = 0;
while ((bytesRead = stream.read(data)) > 0) {
try {
builder.append(new String(data, 0, bytesRead, charset));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Invalid charset: " + e.getMessage());
//Append without charset (uses system's default charset)
builder.append(new String(data, 0, bytesRead));
}
totalRead += bytesRead;
int progress = (int) (totalRead * (100/(double) contentLength));
//Log.d(TAG, "length = " + contentLength + " bytesRead = " + bytesRead + " totalRead = " + totalRead + " progress = " + progress);
publishProgress(progress);
}
} else {
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line + '\n');
publishProgress(100);
}
}
result = builder.toString();
} catch (Exception e) {
Log.e(TAG, "Exception "+e.toString());
} finally {
if(reader != null){
try {
reader.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
if(!this.isCancelled()) command.onProgressUpdate(progress[0]);
}
#Override
protected void onPostExecute(String result){
if(!this.isCancelled()) downloadTaskComplete(result);
}
}
/**
*
* #param data
*/
private void downloadTaskComplete(Object data){
if(!isCanceled){
try {
Log.d(TAG, data.toString());
JSONObject obj = new JSONObject(data.toString());
JSONArray array = obj.getJSONArray("articles");
for(int i = 0; i < array.length(); i++){
SearchResultDO dataObj = new SearchResultDO();
dataObj.title = array.getJSONObject(i).getString("title");
dataObj.url = array.getJSONObject(i).getString("url");
dataObj.snippet = array.getJSONObject(i).getString("summary");
dataObj.source = array.getJSONObject(i).getString("source");
dataObj.date = array.getJSONObject(i).getString("publish_date");
dataObj.termId = currentSearchTermDO.id;
//Reformat date
SimpleDateFormat format1 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
try {
Date date = format1.parse(dataObj.date);
SimpleDateFormat format2 = new SimpleDateFormat(SearchResultDO.DATE_FORMAT_STRING);
dataObj.date = format2.format(date);
} catch(ParseException pe) {
Log.e(TAG, pe.getMessage());
}
results.add(dataObj);
}
} catch(JSONException e){
Log.e(TAG, e.toString());
}
command.serviceComplete(results);
}
}
}
Well, since content length is reported in bytes, there is really no other way. If you want to use a StringReader you could take the length of each line you read and calculate the total bytes read to achieve the same thing. Also, the regular idiom is to check the return value of read() to check if you have reached the end of the stream. If, for some reason, the content length is wrong, your code may read more/less data then available. Finally, when converting a byte blob to a string, you should explicitly specify the encoding. When dealing with HTTP, you can get that from the 'charset' parameter of the 'Content-Type' header.
I had similar problem. I tried the solution of Jeremy C, but it was inaccurate, because value of "Content-Length" from header can be very different than real data.
My solution is:
Send HTTP header from server (PHP):
$string = json_encode($data, JSON_PRETTY_PRINT | JSON_FORCE_OBJECT);
header("X-Size: ".strlen($string)); //for example with name: "X-Size"
print($string);
Read correct value "X-size" for contentLength variable from HTTP header before read from stream:
protected String doInBackground(URL... urls) {
if (General.DEBUG) Log.i(TAG, "WebAsyncTask(doInBackground)");
String result = "";
BufferedReader reader = null;
try {
HttpURLConnection conn = (HttpURLConnection) urls[0].openConnection();
conn.setConnectTimeout(General.TIMEOUT_CONNECTION);
conn.setReadTimeout(General.TIMEOUT_SOCKET);
conn.setRequestMethod("GET");
conn.connect();
if (General.DEBUG) Log.i(TAG, "X-Size: "+conn.getHeaderField("X-Size"));
if (General.DEBUG) Log.i(TAG, "getHeaderField: "+conn.getHeaderFields());
if(conn.getResponseCode() != General.HTTP_STATUS_200)
return General.ERR_HTTP;
int contentLength = -1;
try {
contentLength = Integer.parseInt(conn.getHeaderField("X-Size"));
} catch (Exception e){
e.printStackTrace();
}
InputStream stream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
//Pokud delku zname:
if(contentLength > -1){
byte[] data = new byte[16]; //TODO
int totalRead = 0;
int bytesRead = 0;
while ((bytesRead = stream.read(data)) > 0){
Thread.sleep(100); //DEBUG TODO
try {
builder.append(new String(data, 0, bytesRead, "UTF-8"));
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "Invalid charset: " + e.getMessage());
//Append without charset (uses system's default charset)
builder.append(new String(data, 0, bytesRead));
}
totalRead += bytesRead;
int progress = (int) (totalRead * (100/(double) contentLength));
Log.i(TAG, "length = " + contentLength + " bytesRead = " + bytesRead + " totalRead = " + totalRead + " progress = " + progress);
publishProgress(progress);
}
} else {
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line + '\n');
publishProgress(100);
}
}
result = builder.toString();
} catch (SocketException | SocketTimeoutException e){
if (General.DEBUG) Log.i(TAG, "SocketException or SocketTimeoutException");
e.printStackTrace();
return General.HTTP_TIMEOUT;
} catch (Exception e){
e.printStackTrace();
return General.ERR_HTTP;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
I'm trying to get a csv file from http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2 then parse it so that I can get the price and the price changed into an object that sets both properties. Is there a way that I can do this with the android libraries?
Edit: Here's the current state of the union (not working):
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(uri);
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
String[] RowData = result.split("\n");
String name = RowData[0];
String price = RowData[1];
String change = RowData[2];
stock.setPrice(Double.parseDouble(price));
stock.setTicker(name);
stock.setChange(change);
}
Try something like this:
//--- Suppose you have input stream `is` of your csv file then:
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
date = RowData[0];
value = RowData[1];
// do something with "data" and "value"
}
}
catch (IOException ex) {
// handle exception
}
finally {
try {
is.close();
}
catch (IOException e) {
// handle exception
}
}
Hope this helps.
For the first part:
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
For the second part, Harry is right, just follow his code, or use some libraries: http://commons.apache.org/sandbox/csv/
CSVReader reader = new CSVReader(** Insert your Reader here **);
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
A better CSV parser handles quoted fields
import android.content.Context;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
private class StringDArray {
private String[] data=new String[0];
private int used=0;
public void add(String str) {
if (used >= data.length){
int new_size= used+1;
String[] new_data=new String[new_size];
java.lang.System.arraycopy( data,0,new_data,0,used);
data=new_data;
}
data[used++] = str;
}
public int length(){
return used;
}
public String[] get_araay(){
return data;
}
}
private Context context;
public CSVReader(Context context){
this.context=context;
}
public List read(InputStream inputStream){
List resultList = new ArrayList();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String csvLine;
final char Separator = ',';
final char Delimiter = '"';
final char LF = '\n';
final char CR = '\r';
boolean quote_open = false;
while ((csvLine = reader.readLine()) != null) {
//String[] row = csvLine.split(",");// simple way
StringDArray a=new StringDArray();
String token="";
csvLine+=Separator;
for(char c:csvLine.toCharArray()){
switch (c){
case LF: case CR:// not required as we are already read line
quote_open=false;
a.add(token);
token="";
break;
case Delimiter:
quote_open=!quote_open;
break;
case Separator:
if(quote_open==false){
a.add(token);
token="";
}else{
token+=c;
}
break;
default:
token+=c;
break;
}
}
if(a.length()>0 ) {
if(resultList.size()>0){
String[] header_row =(String[]) resultList.get(0);
if(a.length()>=header_row.length) {
String[] row = a.get_araay();
resultList.add(row);
}
}else{
String[] row = a.get_araay();
resultList.add(row);//header row
}
}
}
inputStream.close();
}catch (Exception e){
Toast.makeText(context,"Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
return resultList;
}
}
Usage
File file=new File(path);
CSVReader csvReader=new CSVReader(activity.this);
List csv=csvReader.read( new FileInputStream(file));
if(csv.size()>0){
String[] header_row =(String[]) csv.get(0);
if(header_row.length>1){
String col1=header_row[0];
String col2=header_row[1];
}
}
Toast.makeText(activity.this,csv.size() + " rows", Toast.LENGTH_LONG).show();
Sample data used
ID,Name
1,Test Item 1
"2","Test Item 2"
"3","Test , Item 3"
4,Test Item 4