Android TextView does not display russian symbols - java

I have a txt file (UTF-8 format) saved at res/raw. When I try to display it's contents in a TextView in my app, I get rubbish instead of russian symbols.
Here's the layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id = "#+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="18sp"
android:padding="5dp"
android:text="#string/hello_world" />
</LinearLayout>
And my code:
package com.example.filereader_sample;
import java.io.DataInputStream;
import java.io.InputStream;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.text);
InputStream file = getResources().openRawResource(R.raw.content);
try {
StringBuffer sBuffer = new StringBuffer();
DataInputStream dataIO = new DataInputStream(file);
String str = null;
while ((str = dataIO.readLine()) != null)
sBuffer.append(str + "\n");
text.setText(sBuffer.toString());
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG);
}
}
}
Is there any way to display russian symbols correctly?

Related

Loading Json data won't show

I am trying to make an app that takes data from google sheet in JSON format.
I have tried a couple of different codes to make the data simply apeare on the screen, but could not make this happen.
would be glad for ideas.
tried with a several codes using AsyncTask and saw it is not working. so tried a
different approach..
the following app is a blank page with a button, that when you click it , it suppose to make name list apear on the screen.
the JSON url:
https://myjson.dit.upm.es/api/bins/1anx
the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="click me!"
android:layout_centerHorizontal="true"
android:layout_margin="50dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginHorizontal="150dp"
android:padding="5dp"
android:textSize="24dp"
android:id="#+id/data"
android:text="list"/>
</ScrollView>
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/userList"
/>
</RelativeLayout>
The ActivityMain.Java :
package com.example.webdownload;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.webdownload.databinding.ActivityMainBinding;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
ArrayList<String> userList;
ArrayAdapter<String> listAdapter;
Handler mainHandler= new Handler();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
initializeUserList();
binding.data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new fetchData().start();
}
});
}
private void initializeUserList() {
userList = new ArrayList<>();
listAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,userList);
binding.userList.setAdapter(listAdapter);
}
class fetchData extends Thread{
String data = "";
#Override
public void run() {
mainHandler.post(new Runnable() {
#Override
public void run() {
progressDialog =new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching Data");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
try {
URL url =new URL("http://myjson.dit.upm.es/api/bins/1anx");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line;
while ((line= bufferedReader.readLine())!= null){
data = data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
JSONArray users = jsonObject.getJSONArray("Users");
userList.clear();
for(int i =0;i<users.length();i++){
JSONObject names = users.getJSONObject(i);
String name = names.getString("name");
userList.add(name);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
mainHandler.post(new Runnable() {
#Override
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
listAdapter.notifyDataSetChanged();
}
});
}
}
}
I Think This is happening because your JSON URL have some spelling mistake
The spelling of name (namr) is wrong
You can check your json url - Your wrong json url

I have made an application to fetch JSON data from a link. But whenever i click on the button , i don't get any data

I have made a button, on which, when i click the data is supposed to show up. But it's not. I don't know what's the problem. I don't get any errors and the app also works fine.
I have already given the internet permission so there no issue for that.
Here are the code files
MainActivity.java
package com.example.apiactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click=(Button) findViewById(R.id.button);
data=(TextView) findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchData process= new fetchData();
process.execute();
}
});
}
}
fetchData.java
package com.example.apiactivity;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data="";
String dataParsed="";
String singleParsed="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url=new URL("https://oneglobal.in/api/UserApi/Login");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line!=null){
line=bufferedReader.readLine();
data= data + line;
}
JSONArray JA=new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO= (JSONObject) JA.get(i);
singleParsed= "Email:" + JO.get("Email") + "\n" + "Password:" + JO.get("Password") + "\n";
dataParsed = dataParsed+ singleParsed + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.data);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CLick me!"
android:id="#+id/button"
android:layout_marginBottom="10dp"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:textSize="24sp"
android:id="#+id/fetcheddata"
android:hint="Fetched data here"
/>
</ScrollView>
</RelativeLayout>
Whenever i click on the button, I want the json data on my screen in table view.
you have to send the user name and the password to the login api
and it is better to use retrofit or even volley to integrate with the remote api

android app crashes while trying to register a user

I'm trying to insert data user to MySQL from the app, as registering a user, but every time it will crash
I changed the code and used one from an instructor in Udemy, but it still.. crashes
I was thinking it's an internet connection problem, but it wasn't.. the internet works just fine.
what I am doing wrong here?
Layout, pRegister
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".pRegister"
android:background="#color/Background">
<EditText
android:id="#+id/pID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="number"
android:hint="#string/regID"
android:backgroundTint="#color/white"
android:textColorHint="#color/white" />
<EditText
android:id="#+id/pPhoneNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/pID"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:importantForAutofill="auto"
android:hint="#string/phoneNo"
android:backgroundTint="#color/white"
android:textColorHint="#color/white" />
<Button
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/pPhoneNo"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:backgroundTint="#color/white"
android:textColor="#color/textButton"
android:textAllCaps="false"
android:text="#string/regbutton"
android:onClick="register"
/>
</RelativeLayout>
java activity,
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class pRegister extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_p_register);
}
// register function
public void register (View view) {
Intent intent = new Intent(this, Insert.class);
startActivity(intent);
}
}
Insert.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
public class Insert extends AppCompatActivity {
EditText eID, ePhoneNo;
String id, phoneNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_p_register);
eID = (EditText) findViewById(R.id.pID);
ePhoneNo = (EditText) findViewById(R.id.pPhoneNo);
}
public void register (View view) {
id = eID.getText().toString();
phoneNo = ePhoneNo.getText().toString();
// for java class background task
String method= "register";
backgroundTask backgroundTask= new backgroundTask(this);
backgroundTask.execute(method,id, phoneNo);
finish();
}
}
background Task.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class backgroundTask extends AsyncTask<String,Void,String> {
Context ctx;
backgroundTask(Context ctx){this.ctx=ctx;}
protected String doInBackground(String... params) {
// background pRegister
String reg_url = "/insert.php";
String method = params[0];
if(method.equals("register")){
String id = params[1];
String phoneNo = params[2];
try {
URL url= new URL(reg_url);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os= httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data= URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(id,"UTF-8")+"&"+
URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(phoneNo,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS= httpURLConnection.getInputStream();
IS.close();
return "Registration success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
insert.php
<?php
require "connect.php";
$id= $_POST["id"];
$phoneNo= $_POST["phoneNo"];
$height= $_POST ["height"];
$weight= $_POST["weight"];
$bloodType= $_POST["bloodType"];
$country= $_POST["country"];
$gender= $_POST["gender"];
$sql = "INSERT into patient (`id`, `phoneNo`) VALUES (`$id`, `$phoneNo`);";
if ($conn->query($sql) === TRUE) {
echo "data added successfully";
} else {
echo "Error adding data: " . $conn->error;
}
$conn->close();
?>

Cannot resolve method setText/getText

So I am still learning Android and Java and I was trying to follow the code on this page: http://www.androidauthority.com/use-remote-web-api-within-android-app-617869/
The thing is that the code they provide does not work for me, and Android Studio says Cannot resolve method for both the setText and the getText methods.
This is my code:
package com.example.beldr.apitest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static com.example.beldr.apitest.R.id.emailText;
import static com.example.beldr.apitest.R.id.responseView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
private ProgressBar progressBar;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL("https://api.fullcontact.com/v2/person.json" + "email=" + email + "&apiKey=" + "126042055");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
And this is the activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.beldr.apitest.MainActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="368dp"
android:layout_height="495dp"
android:orientation="vertical"
tools:context="com.sample.foo.simplewebapi.MainActivity"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="8dp">
<EditText
android:id="#+id/emailText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Enter email address"/>
<Button
android:id="#+id/queryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:text="Search"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:layout_centerHorizontal="true"
android:visibility="gone" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/responseView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</RelativeLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
EDIT: I tried putting
TextView textView=(TextView)findViewById(R.id.responseView);
But then it says Cannot resolve method to the findViewById
TextView responseView = (TextView) findViewById(R.id.responseView);
then you'll be able to .setText() ect
The problem is that you are using those methods from ids and not from objects.
This should be the way:
EditText etEmail = (EditText) findViewById(R.id.emailText);
TextView tvResponse = (TextView) findViewById(R.id.responseView);
Then you can call getText() and setText() from etEmail and tvResponse.
Bonus: remove these lines
import static com.example.beldr.apitest.R.id.emailText;
import static com.example.beldr.apitest.R.id.responseView;
and just use:
import com.example.beldr.apitest.R
Put
TextView textView = (TextView) findViewById(R.id.responseView);
into onCreate() method and make variable TextView textView global in class, so then you can call it from AsyncTask

SetText is not showing text in TextView

I am trying to show the fetched string from arraylist in textview. but it is not showing the string. but when i set text="Some" in my xml file. then it shows the value.
Below i have attached my MainActivity.java and activity_main.xml file.
MainActivity.java:
package com.example.dhara.codesprint;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
//private WordDictionary dictionary;
private static final int DEFAULT_WORD_LENGTH = 3;
private static final int MAX_WORD_LENGTH = 7;
private ArrayList<String> wordList = new ArrayList<>();
private Random random =new Random();
private String currentWord;
private ArrayList<String> words;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText text7 = (EditText) findViewById(R.id.edittext);
Button checkAnswer = (Button) findViewById(R.id.button);
Button reset = (Button) findViewById(R.id.button2);
AssetManager assetManager = getAssets();
try {
InputStream inputStream = assetManager.open("words.txt");
} catch (IOException e) {
Toast toast = Toast.makeText(this, "Could not load dictionary", Toast.LENGTH_LONG);
toast.show();
}
try {
addWord();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addWord() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = in.readLine()) != null) {
String word = line.trim();
if (word.length() == 6) {
wordList.add(word);
}
int x,y,temp;
String str;
x=random.nextInt(wordList.size());
str=wordList.get(x);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText("Text");
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/background"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_alignRight="#+id/imageView1"
android:layout_alignEnd="#+id/imageView1"
android:id="#+id/textView1"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignStart="#+id/imageView1"
android:textAlignment="center"
android:textStyle="normal|bold"
android:textColor="#android:color/background_light" />
</RelativeLayout>
You're suppressing a possible error in addWord()
try {
addWord();
} catch (IOException e) {
e.printStackTrace();
}
where you just create a FileReader on a file words.txt
BufferedReader in = new BufferedReader(new FileReader("words.txt"));
Considering your test
InputStream inputStream = assetManager.open("words.txt");
the first won't find any file. You should load the asset correctly in addWord() too.
InputStreamReader fin = new InputStreamReader(assetManager.open("words.txt"));
BufferedReader in = new BufferedReader(fin);

Categories

Resources