SetText is not showing text in TextView - java

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);

Related

Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}

Main activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#color/colorPrimary"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="#android:color/white"
android:ems="10"
android:hint="Add a Note"
android:textColor="#android:color/black"
android:inputType="textPersonName" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText item;
Button add;
ListView listView;
ArrayList<String> itemList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item = findViewById(R.id.editText);
add = findViewById(R.id.button);
listView = findViewById(R.id.list);
itemList = FileHelper.readData(this);
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,android.R.id.text1,itemList);
listView.setAdapter(arrayAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemName = item.getText().toString();
itemList.add(itemName);
item.setText("");
FileHelper.writeData(itemList,getApplicationContext());
arrayAdapter.notifyDataSetChanged();
}
});
}
}
FileHelper.java
package com.example.myapplication;
import android.content.Context;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class FileHelper {
public static final String FILENAME = "listinfo.dat";
public static void writeData(ArrayList<String> item, Context context)
{
try {
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oas = new ObjectOutputStream(fos);
oas.writeObject(item);
oas.close();
} catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context){
ArrayList<String> itemList = null;
try {
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
itemList = (ArrayList<String>) ois.readObject();
} catch (ClassNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return itemList;
}
}
This gives me an error and the app crashes before it starts
I get the following error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 7111
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
ObjectInputStream ois = new ObjectInputStream(fis);
is returning null. this is not caught in try/catch as well so its crashing

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

Why My Recyclerview Isn't Working In An Acticvity

I need to parse json and show them on RecyclerView.. But my RecyclerView isn't working..
I need to fix this..
This is Json
Simple Json File for My app
[
{
"name": "Saif Maroof",
"roll": 978617,
"gender":"Male",
"phonenumber": 01931078639,
"StudentImage": "R.drawble.books"
},
{
"name": "Minhaj",
"roll": 978617,
"gender":"Male",
"phonenumber": 01931078639,
"studentimage": "R.drawble.books"
}
]
This is StudentInfo Activity
I think in this activity nothing gets wrong
package com.college.npc17_18.activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import com.college.npc17_18.MainActivity;
import com.college.npc17_18.R;
import com.college.npc17_18.adapter.StudentInfoAdapter;
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.util.ArrayList;
import java.util.List;
public class StudentInfo extends AppCompatActivity {
RecyclerView recyclerView;
StudentInfoAdapter studentInfoAdapter;
RecyclerView.Adapter adapter;
// ProgressBar progressBar;
RecyclerView.LayoutManager layoutManager;
List <Object> studentInfo = new ArrayList<>();
DividerItemDecoration dividerItemDecoration;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_info);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// progressBar = findViewById(R.id.progress_circular_country);
recyclerView = findViewById(R.id.studentsInfoRecycleView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new StudentInfoAdapter(this,studentInfo);
// String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "studentinfo.json");
// progressBar.setVisibility(View.GONE);
// studentInfoAdapter = new StudentInfoAdapter(this,studentInfo);
recyclerView.setAdapter(adapter);
addItemsFromJSON();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void addItemsFromJSON() {
try {
String jsonDataString = readJSONDataFromFile();
JSONArray jsonArray = new JSONArray(jsonDataString);
for (int i=0; i<jsonArray.length(); ++i) {
JSONObject itemObj = jsonArray.getJSONObject(i);
String name = itemObj.getString("name");
String roll = itemObj.getString ("roll");
String phonenumber = itemObj.getString("phonenumber");
String gender = itemObj.getString("gender");
int studentimage = itemObj.getInt("studentimage");
com.college.npc17_18.model.StudentInfo studentInfos = new com.college.npc17_18.model.StudentInfo(name,roll,phonenumber,gender,studentimage);
studentInfo.add(studentInfos);
}
} catch (JSONException | IOException e) {
Log.d(TAG, "addItemsFromJSON: ", e);
}
}
private String readJSONDataFromFile() throws IOException{
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonString = null;
inputStream = getResources().openRawResource(R.raw.studentinfo);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonString = bufferedReader.readLine()) != null) {
builder.append(jsonString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
This is StudentInfo Adapter
package com.college.npc17_18.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.college.npc17_18.R;
import com.college.npc17_18.model.StudentInfo;
import java.util.ArrayList;
import java.util.List;
public class StudentInfoAdapter extends RecyclerView.Adapter <StudentInfoAdapter.Viewholder> {
private List <Object> studentInfos;
Context context;
public StudentInfoAdapter(Context context, List<Object> studentInfo) {
this.studentInfos = studentInfo;
this.context = context;
}
#NonNull
#Override
public StudentInfoAdapter.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.studentitem,parent,false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull StudentInfoAdapter.Viewholder holder, int position) {
StudentInfo studentInfo = (StudentInfo) studentInfos.get(position);
holder.StudentImageId.setImageResource (studentInfo.getStudentImage());
holder.NameId.setText("Name:"+studentInfo.getNamme());
holder.RollId.setText("Roll"+studentInfo.getRoll());
holder.GenderId.setText("Gender:"+studentInfo.getGender());
holder.PhoneNumberId.setText("Phone Number:"+studentInfo.getPhoneNumber());
}
#Override
public int getItemCount() {
return studentInfos.size();
}
public class Viewholder extends RecyclerView.ViewHolder{
TextView NameId,RollId,PhoneNumberId,GenderId;
ImageView StudentImageId;
public Viewholder(#NonNull View itemView) {
super(itemView);
StudentImageId = itemView.findViewById(R.id.StudentImageId);
NameId = itemView.findViewById(R.id.NameId);
RollId = itemView.findViewById(R.id.RollId);
// CGPAId = itemView.findViewById(R.id.CGPAId);
GenderId = itemView.findViewById(R.id.GenderId);
PhoneNumberId = itemView.findViewById(R.id.PhoneNumberId);
}
}
}
This is StudentItem.xml
Layout for RecyclerView...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:clickable="true"
android:elevation="40dp"
app:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/StudentImageId"
android:layout_width="71dp"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/NameId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="18sp" />
<TextView
android:id="#+id/RollId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Roll" />
<TextView
android:id="#+id/GenderId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gender" />
<TextView
android:id="#+id/PhoneNumberId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Phone Number" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Now what do I need to do?
At the time when you instantiate an object of your adapter class
adapter = new StudentInfoAdapter(this,studentInfo);
Your adapter object is initialized with an empty studentInfo list
So, you should call adapter.notifyDataSetChanged(); in your addItemsFromJSON() method when the JSON parsing is completed.
update your adapter after you set your data
yourAdapter.notifyDataSerChanged();

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 TextView does not display russian symbols

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?

Categories

Resources