How to convert Shift-JIS encoded string to UTF-8? - android

I am getting html source from Aozora Bunko. Html file is Shift-JIS encoded. I am trying to get book title and author. Then I want to record title and author into SQLite(UTF-8) database.
String[] splittedResult = result.split("\"title\">");
splittedResult = splittedResult[1].split("</h1>");
String title = splittedResult[0];
byte[] b = null;
try {
b = title.getBytes("Shift_JIS");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String value=null;
try {
value = new String(b, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
...
myDatabase.addBookInformation(value, author);
Result is like this: latin letters are showing normally. But japanese letters are shown by blocks question mark inside (please do not pay attention to null values)
How to solve this problem?

As #Codo pointed out, solution for this problem was before.
I changed this
s = EntityUtils.toString(response.getEntity(), "UTF-8");
to this
s = EntityUtils.toString(response.getEntity(), "Shift_JIS");
And now there is no need for encoding.
String[] splittedResult = result.split("\"title\">");
splittedResult = splittedResult[1].split("</h1>");
String title = splittedResult[0];
/** I HAVE TAKEN THIS PART OF MY CODE
byte[] b = null;
try {
b = title.getBytes("Shift_JIS");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String value=null;
try {
value = new String(b, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
**/

Related

OpenCSV read specific column

i am facing small problem while using OPENCSV and trying to read specific column from a line. I have a csv file that looks like this
"ID","Name","Name2","Date","Author"
"1","Alex","Example","18.3.2016","Alex"
Now i want to read only the column 2 and 3 (Name and Name2).
My code looks like this
try {
CSVReader reader = new CSVReader(new FileReader(filelocation));
String [] nextLine;
int rowNumber = 0;
while ((nextLine = reader.readNext()) != null) {
rowNumber++;
for(int i = 0; i< nextLine.length ; i++){
System.out.println("Cell index: " + i);
System.out.println("Cell Value: " + nextLine[i]);
System.out.println("---");
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I already tried setting the "i" variable manually to 1 and 2. But then i am getting 4 same results shown in log. What is missing? Thanks!
Never mind, i found the trick.
Here is how it should look.
try {
CSVReader reader = new CSVReader(new FileReader(filelocation));
String [] nextLine;
int rowNumber = 0;
while ((nextLine = reader.readNext()) != null) {
rowNumber++;
String name = nextLine[1];
String name2 = nextLine[2];
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After it, i could get the string value and work with it.

Huge string to HTML

I`m trying to get a String from URL and create an objects by Gson. I am getting to string from this url: http://gotachles.co.il/data.php and then I have to convert it to html before sending it to Gson. The problem is that my string is probably too long (1.5 million letters) and the app freeze when calling fromHTML. (tried and it works fine with smaller strings).
TachlesStringGetter:
class TachlesStringGetter extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String myJSONString = null;
try {
myJSONString = new Scanner(new URL(
"http://gotachles.co.il/data.php").openStream(), "UTF-8")
.useDelimiter("\\A").next();
Log.i("TACHLESSTRINGGETTER", "got sucessfuly");
Log.i("TACHLESSTRINGGETTER", "" + myJSONString.length());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("TACHLESSTRINGGETTER", "RETURN");
return myJSONString;
}
}
The HTML asynctask:
public class FromHTML extends AsyncTask<String, String, String> {
private Spanned spanned;
private String result;
#Override
protected String doInBackground(String... html) {
Log.i("FROMHTML", "STARTING");
spanned = Html.fromHtml(html[0]);
result = spanned.toString();
Log.i("FROMHTML", "Returning");
return result;
}
}
Calling it like that:
public void Jsonnn() {
// sending to anynctask
try {
myJSONString2 = new TachlesStringGetter().execute(myJSONString2)
.get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
// // from html
if (myJSONString2 != null) {
Log.i("WEBVIEWCLASS", "DOING HTML STUFF");
try {
afterHTML = new FromHTML().execute(myJSONString2).get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
Log.i("FINALLY", "STARTING SEOND FINALLY");
try {
Gson gson = new Gson();
JsonObj obj = gson.fromJson(afterHTML, JsonObj.class);
Toast.makeText(getApplicationContext(), obj + "", 2000)
.show();
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "oops jsno!",
1000).show();
}
}
}// first finnaly
}// second finnaly
}
Sorry for the shitty code :D
StringBuilder consume less memory than using String addition (str = str1 + str2). An example use of a StringBuilder:
StringBuilder builder = new StringBuilder();
builder.append("This is my string");
To get your long string from your builder (when you are trying to convert it to Gson object) you can simply call builder.toString();
So you should edit your Asynctask class "TachlesStringGetter" which should use a StringBuilder, you should also change other aspects of your code whenever you use something to append to String. The + operator uses public String concat(String str) internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent. Hope this helps!

Write exif data to android video files

I am extracting metadata information (Exif infor) by using Id3 library in android, but I am getting null pointer exception and getting null in log Message it is a reason because value in src_set is null .I am not getting why it is returning null. my code is :
File src = new File(pathdata);
MusicMetadataSet src_set = null;
try {
src_set = new MyID3().read(src);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // read metadata
if (src_set == null) // perhaps no metadata
{
Log.i("NULL", "NULL");
}
else
{
try{
IMusicMetadata metadata = src_set.getSimplified();
String artist = metadata.getArtist();
String album = metadata.getAlbum();
String song_title = metadata.getSongTitle();
Number track_number = metadata.getTrackNumber();
Log.i("artist", artist);
Log.i("album", album);
}catch (Exception e) {
e.printStackTrace();
}
File dst = new File(pathdata);
MusicMetadata meta = new MusicMetadata("name");
meta.setAlbum("Chirag");
meta.setArtist("CS");
try {
new MyID3().write(src, dst, src_set, meta);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ID3WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // write updated metadata
}

Go to newline in android with HTMLViewer

I will store a data in a file.and i will display it.But my problem is how can i control the HTMLVewr or other reader to go a newline.
in this code when i display the file "file1" there are no newline.
try {
FileOutputStream ops=openFileOutput("file1",Context.MODE_PRIVATE);
DataOutputStream dos=new DataOutputStream(ops);
for(int i=0;i<w*h;i++){
//int alpa=Color.alpha(pixels[i]);
int red=Color.red(pixels[i]);
int green=Color.green(pixels[i]);
int blue=Color.blue(pixels[i]);
String k;
if(i==0)
k=red+" "+green+" "+blue+" ";
else if((i%(w-1)==0)&&(i>0)){
k="**"+red+" "+green+" "+blue+" ";
k=k+"/n";}
else
k="**"+red+" "+green+" "+blue+" ";
dos.write(k.getBytes());
}
ops.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Button text and string from text file (from asset) should be the same, but not in Android

I would like to make a quiz program. The questions are in a text file in asset folder. The answers are also in the asset folder called the number of the question (for example: the first question answers are in the text file called 1). I would like to give the questions and answers randomly (answers to a button). Until this everything is all right (maybe not the shortest solution, but works well). Then the user can answer the question clicking the correct button. And here is the problem. I get the text of the button and the first row of the answer file (always the first row is the right answer in the answer text file). It should be the same, and then I sign, this is the correct answer. But it's not the same, and I don't know why. A put text to the button from the answer file and get the first row from the answer file, so it should be the same. I print it out to log cat, and look like they are the same. I don't know what could be went wrong.
Can anybody help me out.
This is where I set the text of the button (randomly) and compare the first rows and the text of the button:
BufferedReader br2 = new BufferedReader(is2, 8192);
for(int k2=0; k2<3; k2++){
try {
kerdes2[k2] = br2.readLine();
final ArrayList <Integer> kerdesno2 = new ArrayList<Integer>();
for(int j=0;j<3;j++) kerdesno2.add(j);
Collections.shuffle(kerdesno2);
System.out.println(kerdesno2);
answ.setText(kerdes2[kerdesno2.get(0)]);
answ2.setText(kerdes2[kerdesno2.get(1)]);
answ3.setText(kerdes2[kerdesno2.get(2)]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
answ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
InputStreamReader is3 = null;
try {
is3 = new InputStreamReader(am.open(i3), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br3 = new BufferedReader(is3, 8192);
try {
String helyes = br3.readLine();
System.out.println(helyes);
String gomb = answ.getText().toString();
System.out.println(gomb);
for(int f=0; f<helyes.length(); f++)
{
char c = helyes.charAt(f);
char d = gomb.charAt(f);
if(c != d){
System.out.println(c);
System.out.println(((String) gomb).indexOf(c));
}
}
if(gomb == helyes)
{
x++;
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText("Eredményed: " + Math.round(x*100/i2) + "%");
}
else
{
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText(gomb + " = " + helyes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
answ2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
InputStreamReader is3 = null;
try {
is3 = new InputStreamReader(am.open(i3), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br3 = new BufferedReader(is3, 8192);
try {
String helyes = br3.readLine();
System.out.println(helyes);
String gomb = answ2.getText().toString();
System.out.println(gomb);
if(gomb == helyes)
{
x++;
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText("Eredményed: " + Math.round(x*100/i2) + "%");
}
else
{
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText(gomb + " = " + helyes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
answ3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
InputStreamReader is3 = null;
try {
is3 = new InputStreamReader(am.open(i3), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br3 = new BufferedReader(is3, 8192);
try {
String gomb = answ3.getText().toString();
String helyes = br3.readLine();
System.out.println(gomb);
System.out.println(helyes);
if(gomb == helyes){
x++;
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText("Eredményed: " + Math.round(x*100/i2) + "%");
}
else
{
TextView eredmeny = (TextView)findViewById(R.id.eredmeny);
eredmeny.setText(gomb + " = " + helyes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
As You can see I try to iterate over the two strings to realize where the problem is, but I couldn't manage to find...
String is an object. When comparing objects, use .equals(), not ==.
Your code:
if(gomb == helyes)
Should be:
if(gomb.equals(helyes))
By using == you're comparing memory, not the actual String objects. Sometimes you'll get the expected result, but other times you won't. .equals() will always test the Strings themselves.
I can see you are comparing by
if(gomb == helyes){
while it should be
if(gomb.equals(helyes)){

Categories

Resources