Android reading text fie from sdcsrd and store it in ArrayList - android-widget

I need help on this one, I am trying to read a text file stored in sdcard and store the result in an ArrayList for subsequent usage, but the code is crashing.
public class Mytextreader extends Activity {
final ArrayList> dataList = new ArrayList>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadData();
String text = "";
for (int i = 0; i < dataList.size(); i++) {
text = text + dataList.get(i).get("name") + ":"
+ dataList.get(i).get("image") + ":"
+ dataList.get(i).get("price") + ":"
+ dataList.get(i).get("barcode") + "\n";
}
TextView txv = (TextView) findViewById(R.id.textView01);
txv.setText(text);
}
private void loadData() {
File sdcardDir = Environment.getExternalStorageDirectory();
String sdcard = sdcardDir.getAbsolutePath();
File file = new File(sdcard + "/Downloads/data/data.txt");
// For each entry the following lines are repeated
HashMap<String, String> hmap = new HashMap<String, String>();
String text = "", line = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text = text + line + "\n";
}
br.close();
} catch (IOException e) {
Log.d("File Read test: Error= ", e.getMessage());
}
while (true) {
line = text.substring(0, text.indexOf('\n'));
text = text.substring(text.indexOf('\n') + 1);
hmap.put("name", line.substring(0, line.indexOf(';')));
line = line.substring(line.indexOf(';') + 1);
// Toast.makeText(this, line, Toast.LENGTH_LONG).show();
hmap.put("image", line.substring(0, line.indexOf(';')));
line = line.substring(line.indexOf(';') + 1);
// Toast.makeText(this, line, Toast.LENGTH_LONG).show();
hmap.put("price", line.substring(0, line.indexOf(';')));
line = line.substring(line.indexOf(';') + 1);
// Toast.makeText(this, line, Toast.LENGTH_LONG).show();
hmap.put("barcode", line);
dataList.add(hmap);
hmap.clear();
if (text.length() == 0)
break;
}
}
}

Ok fixed, the text file has an empty line, removed that line and the code is ok now

Related

Eclipse Plugin change Language programmatically

I am trying to change the language of my RCP plugin programmatically. I had no luck so far. The Approach below is not working for me. After restart the language does not change. I populate a Menu dynamically with listet Translation files in a specific folder. The method LanguageSelectedListener.widgetSelected when a MenuItem is selected. Tried this with an exported product and also running from eclipse.
private void setMenuLanguages(Menu menu){
File dir = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + language_directory);
String[] dirList = dir.list();
String currentLocale = System.getProperty("user.language");
Locale current = new Locale(currentLocale, "", "");
Locale[] locales = new Locale[dirList.length];
LanguageSelectedListener listener = new LanguageSelectedListener();
for(int i=0; i<dirList.length; i++){
String file = dirList[i].split(".properties")[0];
String locShort;
if(file.equals("messages"))locShort = "en"; //default english
else locShort = file.split("_")[1];
locales[i] = new Locale(locShort);
MenuItem menuItem = new MenuItem(menu, SWT.RADIO, i);
menuItem.setText(locales[i].getDisplayName());
menuItem.setData("locale", locales[i]);
menuItem.addSelectionListener(listener);
if(locales[i].getLanguage().equals(current.getLanguage()))
menuItem.setSelection(true);
}
return;
}
private class LanguageSelectedListener extends SelectionAdapter{
#Override
public void widgetSelected(SelectionEvent e) {
MenuItem item = (MenuItem) e.widget;
if(!item.getSelection() || !MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Info", "Programm wird neu gestartet. Möchten Sie fortfahren?")){
item.setSelection(false);
return;
}
Locale locale = (Locale) item.getData("locale");
StringBuffer arguments = new StringBuffer();
arguments.append("${eclipse.vm}\n"); //$NON-NLS-1$
arguments.append("-nl\n").append(locale.getLanguage()).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
System.setProperty("eclipse.exitcode", Integer.toString(IApplication.EXIT_RELAUNCH)); //$NON-NLS-1$
System.getProperties().setProperty(IApplicationContext.EXIT_DATA_PROPERTY, arguments.toString());
PlatformUI.getWorkbench().restart();
}
}
so I implemented the hacky solution by manipulating the ini file of the product (not the config.ini file). Works pretty well for me.
String installLoc = Platform.getInstallLocation().getURL().getPath();
String oldIniLocation = installLoc + "decoder.ini";
String content = null;
File oldIni = null;
try {
oldIni = new File(oldIniLocation);
content = FileUtils.readFileToString(oldIni, "UTF-8");
} catch (IOException e1) {
throw new RuntimeException("reading from file failed!", e1);
}
Locale locale = (Locale) item.getData("locale");
if(content.contains("-nl")){
content = content.replaceFirst("-nl\r\n..", "-nl\r\n" + locale.getLanguage());
}
else{
StringBuilder newContent = new StringBuilder("-nl\r\n" + locale.getLanguage() +"\r\n");
content = newContent.append(content).toString();
}
File newIni = new File(installLoc + "rename.ini");
try {
FileUtils.writeStringToFile(newIni, content, "UTF-8");
} catch (IOException e1) {
throw new RuntimeException("writing to file failed!", e1);
}
oldIni.delete();
//renaming newIni by moving it
oldIni = new File(installLoc + "decoder.ini");
try {
FileUtils.moveFile(newIni, oldIni);
} catch (IOException e1) {
throw new RuntimeException("renaming/moving file failed!", e1);
}
System.setProperty("eclipse.exitcode", Integer.toString(IApplication.EXIT_RESTART)); //$NON-NLS-1$
PlatformUI.getWorkbench().restart();

java characters upper and lower case

Each character should switch between upper and lower case. My issue is that I cannot get it to work properly. This is what I have so far:
oneLine = br.readLine();
while (oneLine != null){ // Until the line is not empty (will be when you reach End of file)
System.out.println (oneLine); // Print it in screen
bw.write(oneLine); // Write the line in the output file
oneLine = br.readLine(); // read the next line
}
int ch;
while ((ch = br.read()) != -1){
if (Character.isUpperCase(ch)){
Character.toLowerCase(ch);
}
bw.write(ch);
}
Here you go. You had a few problems:
You were never actually storing the result of the character case switch.
You needed to save the line return with each row
I broke out the case switch to make it easier to read
Here's the modified code:
public static void main(String args[]) {
String inputfileName = "input.txt"; // A file with some text in it
String outputfileName = "output.txt"; // File created by this program
String oneLine;
try {
// Open the input file
FileReader fr = new FileReader(inputfileName);
BufferedReader br = new BufferedReader(fr);
// Create the output file
FileWriter fw = new FileWriter(outputfileName);
BufferedWriter bw = new BufferedWriter(fw);
// Read the first line
oneLine = br.readLine();
while (oneLine != null) { // Until the line is not empty (will be when you reach End of file)
String switched = switchCase(oneLine); //switch case
System.out.println(oneLine + " > "+switched); // Print it in screen
bw.write(switched+"\n"); // Write the line in the output file
oneLine = br.readLine(); // read the next line
}
// Close the streams
br.close();
bw.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
public static String switchCase(String string) {
String r = "";
for (char c : string.toCharArray()) {
if (Character.isUpperCase(c)) {
r += Character.toLowerCase(c);
} else {
r += Character.toUpperCase(c);
}
}
return r;
}

iText rotation creates pdf which displays out of memory exception

Following is a code snippet creating a pdf file where pages could be rotated in the resulting file. This works fine for most pdf files. But one particualr pdf file of version 1.6 the page is already rotated by 180, on applying further rotation to it e.g. 90 degress and saving the file causes it to get corrupted. Infact even if you don't rotate the file and simply write it out to another file using iText the file the resulting pdf is corrupted and displays an out of memory exception when opened in Adobe reader.
Why would that happen? Am I missing some sort of compression in the file.
private String createPdfFileWithoutForms(final EditStateData[] editStateData, final String directory)
throws EditingException {
Long startTime = System.currentTimeMillis();
File pdfFileToReturn = new File(directory + File.separator + UidGenerator.generate() + ".pdf");
com.lowagie.text.Document document = null;
FileOutputStream outputStream = null;
PdfCopy pdfCopy = null;
PdfReader reader = null;
PdfDictionary pageDict = null;
int rotationAngle = 0;
Map<Integer, Integer> rotationQuadrants = null;
try {
document = new com.lowagie.text.Document();
outputStream = new FileOutputStream(pdfFileToReturn);
pdfCopy = new PdfCopy(document, outputStream);
pdfCopy.setFullCompression();
pdfCopy.setCompressionLevel(9);
document.open();
for (EditStateData state : editStateData) {
try {
reader = new PdfReader(state.getFileName());
reader.selectPages(state.getPages());
rotationQuadrants = state.getRotationQuadrants();
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
// Rotation quadrant key is the source page number
if (rotationQuadrants.containsKey(state.getPages().get(i - 1))) {
rotationAngle = reader.getPageRotation(i);
pageDict = reader.getPageN(i);
pageDict.put(PdfName.ROTATE,
new PdfNumber((rotationAngle
+ rotationQuadrants.get(state.getPages().get(i - 1))) % 360));
}
document.setPageSize(reader.getPageSizeWithRotation(i));
document.newPage();
// import the page from source pdf
PdfImportedPage page = pdfCopy.getImportedPage(reader, i);
// add the page to the destination pdf
pdfCopy.addPage(page);
}
} catch (final IOException e) {
LOGGER.error(e.getMessage(), e);
throw new EditingException(e.getMessage(), e);
} finally {
if (reader != null) {
reader.close();
}
}
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new EditingException(e.getMessage(), e);
} finally {
if (document != null) {
document.close();
}
if (pdfCopy != null) {
pdfCopy.close();
}
IoUtils.closeQuietly(outputStream);
}
LOGGER.debug("Combining " + editStateData.length + " pdf files took "
+ ((System.currentTimeMillis() - startTime) / 1000) + " msecs");
return pdfFileToReturn.getAbsolutePath();
}

My custome list view not update with new data

Hello I created a custom list view and for update used notifyDataSetChanged() method but my list not updated. please help me.
this is my source code
public class fourthPage extends ListActivity {
ListingFeedParser ls;
List<Listings> data;
EditText SearchText;
Button Search;
private LayoutInflater mInflater;
private ProgressDialog progDialog;
private int pageCount = 0;
String URL;
ListViewListingsAdapter adapter;
Message msg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle b = getIntent().getExtras();
URL = b.getString("URL");
Log.i("Ran->URL", "->" + URL);
MYCITY_STATIC_DATA.fourthPage_main_URL = URL;
final ListingFeedParser lf = new ListingFeedParser(URL);
Search = (Button) findViewById(R.id.searchButton);
SearchText = (EditText) findViewById(R.id.search);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(SearchText.getWindowToken(), 0);
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
progDialog = ProgressDialog.show(this, "",
"Loading please wait....", true);
progDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
data = lf.parse();
} catch (Exception e) {
e.printStackTrace();
}
msg = new Message();
msg.what = 1;
fourthPage.this._handle.sendMessage(msg);
}
}).start();
Search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SearchText = (EditText) findViewById(R.id.search);
if (SearchText.getText().toString().equals(""))
return;
CurrentLocationTimer myLocation = new CurrentLocationTimer();
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(final Location location) {
Toast.makeText(
getApplicationContext(),
location.getLatitude() + " "
+ location.getLongitude(),
Toast.LENGTH_LONG).show();
String URL = "http://75.125.237.76/phone_feed_2_point_0_test.php?"
+ "lat="
+ location.getLatitude()
+ "&lng="
+ location.getLongitude()
+ "&page=0&search="
+ SearchText.getText().toString();
Log.e("fourthPage.java Search URL :->", "" + URL);
Bundle b = new Bundle();
b.putString("URL", URL);
Intent it = new Intent(getApplicationContext(),
fourthPage.class);
it.putExtras(b);
startActivity(it);
}
};
myLocation.getLocation(getApplicationContext(),
locationResult);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"No data available for this request", Toast.LENGTH_LONG)
.show();
}
}
private Handler _handle = new Handler() {
#Override
public void handleMessage(Message msg) {
progDialog.dismiss();
if (msg.what == 1) {
if (data.size() == 0 || data == null) {
Toast.makeText(getApplicationContext(),
"No data available for this request",
Toast.LENGTH_LONG).show();
}
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
adapter = new ListViewListingsAdapter(getApplicationContext(),
R.layout.list1, R.id.title, data, mInflater);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(),
"Error in retrieving the method", Toast.LENGTH_SHORT)
.show();
}
}
};
public void onListItemClick(ListView parent, View v, int position, long id) {
// remember i m going from bookmark list
MYCITY_STATIC_DATA.come_from_bookmark = false;
Log.i("4thPage.java - MYCITY_STATIC_DATA.come_from_bookmark",
"set false - > check" + MYCITY_STATIC_DATA.come_from_bookmark);
Listings sc = (Listings) this.getListAdapter().getItem(position);
if (sc.getName().equalsIgnoreCase("SEE MORE...")) {
pageCount = pageCount + 1;
final ListingFeedParser lf = new ListingFeedParser((URL.substring(
0, URL.length() - 1)) + pageCount);
try {
progDialog = ProgressDialog.show(this, "",
"Loading please wait....", true);
progDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
data.remove(data.size() - 1);
data.addAll(lf.parse());
Message msg = new Message();
msg.what = 1;
fourthPage.this._handle.sendMessage(msg);
}
}).start();
} catch (Exception e) {
pageCount = pageCount - 1;
// TODO: handle exception
Toast newToast = Toast.makeText(this, "Error in getting Data",
Toast.LENGTH_SHORT);
}
} else {
Bundle b = new Bundle();
b.putParcelable("listing", sc);
Intent it = new Intent(getApplicationContext(),
FifthPageTabbed.class);
it.putExtras(b);
startActivity(it);
}
}
#Override
public void onBackPressed() {
setResult(0);
finish();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e("RESUME:-)", "4th Page onResume");
try {
//adapter.notifyDataSetChanged();
//setListAdapter(adapter);
//getListView().setTextFilterEnabled(true);
} catch (Exception e) {
Log.e("EXCEPTION in 4th page",
"in onResume msg:->" + e.getMessage());
}
}
}
Do not re-create the object of ArrayList or Array you are passing to adapter, just modify same ArrayList or Array again. and also when array or arrylist size not changed after you modify adapter then in that case notifydatasetchange will not work.
In shot it is work only when array or arraylist size increases or decreases.
What version of Android are you targeting? The latest version seems to have revised how notifyDataSetChanged() works. If you target sdk 11 it might work?
Also, there seems to be a different (and very thorough answer) to this question in another post:
notifyDataSetChanged example

How to dynamically draw a TableLayout from AsyncTask

My question is as the title states, I dynamically draw a table when I press a button and it works. But due to the fact that I need to show a process dialog while the table is being drawn I have tried using AsyncTask and it keeps crashing in the doInBackground() function.
Can anyone perhaps tell me what I am doing wrong?
private class TransactionsTask extends AsyncTask<Long, Void, Void>
{
final TextView[] tx = new TextView[10];
final TableRow[] tr = new TableRow[10];
final TableLayout tl = (TableLayout)findViewById(R.id.maintable);
final ProgressDialog dialog = ProgressDialog.show(TransactionsActivity.this, "", "Retrieving...", true);
protected void onPreExecute()
{
this.dialog.show();
}
protected Void doInBackground(Long... params)
{
// A request for all transactions on the specified data is made to the S-Qube here
com.example.sqube.SettingsActivity.out.println(c + "0130;EmployeeId=4;LastTXId=0;FirstTXId=0;SYear=11;SMon=" + (mStartMonth + 1) + ";SDay=" + mStartDay + ";EYear=11;EMon=" + (mEndMonth + 1) + ";EDay=" + mEndDay + ";Area=0;View=1;TXType=1;" + d);
com.example.sqube.SettingsActivity.out.flush();
while(control == false)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
tl.removeAllViews(); // The view is first cleared before drawn again
// This code it used to dynamically draw the transactions table based on the number of transactions received from the S-Qube
tr[0] = new TableRow(TransactionsActivity.this);
tr[1] = new TableRow(TransactionsActivity.this);
tr[2] = new TableRow(TransactionsActivity.this);
tr[3] = new TableRow(TransactionsActivity.this);
tx[0] = new TextView(TransactionsActivity.this);
tx[1] = new TextView(TransactionsActivity.this);
tx[2] = new TextView(TransactionsActivity.this);
tx[3] = new TextView(TransactionsActivity.this);
tx[0].setText("Date ");
tx[0].setTextColor(Color.BLACK);
tx[0].setTypeface(null, 1);
tr[0].addView(tx[0]);
tx[1].setText("Device ");
tx[1].setTextColor(Color.BLACK);
tx[1].setTypeface(null, 1);
tr[0].addView(tx[1]);
tx[2].setText("Access Type ");
tx[2].setTextColor(Color.BLACK);
tx[2].setTypeface(null, 1);
tr[0].addView(tx[2]);
tx[3].setText("Areas ");
tx[3].setTextColor(Color.BLACK);
tx[3].setTypeface(null, 1);
tr[0].addView(tx[3]);
tl.addView(tr[0], new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tl.addView(tr[1], new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tl.addView(tr[2], new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tl.addView(tr[3], new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
for(i = 0; i < com.example.sqube.SettingsActivity.Count1; i++)
{
tr[i] = new TableRow(TransactionsActivity.this);
tx[0] = new TextView(TransactionsActivity.this);
tx[1] = new TextView(TransactionsActivity.this);
tx[2] = new TextView(TransactionsActivity.this);
tx[3] = new TextView(TransactionsActivity.this);
tx[0].setText(Date[i] + " ");
tx[0].setTextColor(Color.BLACK);
tx[0].setTypeface(null, 1);
tx[1].setText(Device[i] + " ");
tx[1].setTextColor(Color.BLACK);
tx[1].setTypeface(null, 1);
tx[2].setText(Access_Type[i] + " ");
tx[2].setTextColor(Color.BLACK);
tx[2].setTypeface(null, 1);
tx[3].setText(Area[i] + " ");
tx[3].setTextColor(Color.BLACK);
tx[3].setTypeface(null, 1);
tr[i].addView(tx[0]);
tr[i].addView(tx[1]);
tr[i].addView(tx[2]);
tr[i].addView(tx[3]);
tl.addView(tr[i], new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
com.example.sqube.SettingsActivity.Count1 = 0;
control = false;
return null;
}
protected void onPostExecute(final Void unused)
{
dialog.dismiss();
}
}