The contents of the string descript is showing up in logcat with no problems but won't display on the textview in the dialog located in OnPostExecute. It's a nullpointer exception. I'm not sure why since the episode string works just fine. Can anyone tell me why?
class getDescContent extends AsyncTask<Void, Void, Void> {
FileInputStream input = null;
String episode = null;
String descript = null;
#Override
protected Void doInBackground(Void... arg0) {
try {
input = new FileInputStream(descFile);
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {
if (line.length() < 50) {
episode = line;
continue;
}
descript = line;
Log.i("", descript);
}
input.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.info_dialog);
dialog.setTitle(episode);
TextView descrip = (TextView) findViewById(R.id.dialog_text);
descrip.setText(descript);
dialog.show();
}
}
You should use
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.info_dialog);
dialog.setTitle(episode);
TextView descrip = (TextView) dialog.findViewById(R.id.dialog_text); //change in this line
descrip.setText(descript);
dialog.show();
Since the textview is not in the layout of the activity but in the layout of the dialog.
In your code, descrip is null, because it cannot be found.
Related
In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.
I have a method which gets a string from a file and puts it inside String variable named username, because the reading from the file takes time, I want a progressDialog to appear untill the function is finished, the preogress dialog does appear but is not dismissed when I use progressDialog.dismiss();
This is the code:
public String loadUserFromFile(){
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait...");
progressDialog.setMessage("Loading User");
progressDialog.show();
String username = "default";
String fileName = "savedUserFile.txt";
FileInputStream fis;
try {
fis = openFileInput(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(inputStreamReader);
username = br.readLine();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
username = username.replaceAll("\\s+","");
progressDialog.dismiss();
return username;
}
The 1st thing to make sure that dialog is not null.
ProgressDialog mProgressDialog;
mProgressDialog = new ProgressDialog(thisActivity);
mProgressDialog.setCancelable(false);
//If you want to show progress dialog
public void showProgressDialog(String message) {
if (mProgressDialog != null) {
mProgressDialog.setMessage(message);
mProgressDialog.show();
}
}
//To dismiss progress dialog
public void dismissProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
Usage:
showProgressDialog("Loading");
or
dismissProgressDialog();
I got a question that I don't know how to solve.
I am trying to achieve putting the 'question' and 'answer' into the 2D Array, but it cannot put the data into the 2D array in the asyncTask.
I am expecting I can put the 'question' and 'answer' that get in JSON Object into the 2D array. And then use the array in OnCreate method.
public class MainActivity extends Activity {
String[][] array = new String[10][4];
private TextView tvData;
int qnum = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
String quest;
String ans;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONTask().execute("http://itdmoodle.hung0530.com/ptms/questions_ws.php");
Button btnNext = (Button) findViewById(R.id.btnNext);
tvData = (TextView) findViewById(R.id.textView);
for(int i=0;i<10;i++){
int z = i+1;
array[i][0] = String.valueOf(z);
}
quest = array[0][1];
ans = array[0][2];
tvData.setText(quest);
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
public class JSONTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String Json = buffer.toString();
JSONObject jsonObject = new JSONObject(Json);
JSONArray jsonArray = jsonObject.getJSONArray("Questions");
StringBuffer bufferQues = new StringBuffer();
StringBuffer bufferAns = new StringBuffer();
for(int i=0;i<jsonArray.length();i++) {
JSONObject otherJson = jsonArray.getJSONObject(i);
String question = otherJson.getString("question");
String answer = otherJson.getString("answer");
bufferQues.append(question);
bufferAns.append(answer);
array[i][1] = bufferQues.toString();
array[i][2] = bufferAns.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(conn != null){
conn.disconnect();
}
try{
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
}
Asynctask executes asynchronously. It allows you to perform long running operations on a background thread(doInBackground is run on a seperate thread than main thread) and use the results to perform operations on main thread(onPostExecute runs on main thread).
What you want is to perform the operation on your 2D array in onPostExecute and not in onCreate.
I have this code below: I want to view every line by line in textview but there is a problem,
public class Resulat2 extends Activity {
private Handler h = new Handler();
private Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newee);
try {
File file2 = new File(Ppp.path);
FileReader fileReader = new FileReader(file2);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
final ScrollView scrollview = (ScrollView) findViewById(R.id.scrollView);
final TextView textview = (TextView) findViewById(R.id.textView10);
final StringBuilder sb = new StringBuilder("");
while ((line = bufferedReader.readLine()) != null){
final String finalLine = line;
new Thread(new Runnable() {
public void run() {
sb.append(finalLine);
sb.append("\n");
Log.d("testing5", finalLine);
}
}).start();
Thread.sleep(1000);
}
runOnUiThread(new Runnable() {
public void run() {
textview.setText(sb.toString());
textview.setMovementMethod(new ScrollingMovementMethod());
scrollview.post(new Runnable() {
#Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
});
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
When I run, the log.d works perfectly but the textview is not shown.
your update for the textview has a minor flaw, it runs only once and then stops...
a simple solution might be introducing a boolean or (even more simply) check if your 'line' not is null...
runOnUiThread(new Runnable() {
public void run() {
while(line!= null){
textview.setText(sb.toString());
//...
Thread.sleep(200) //let other processes have some cpu
}
});
}
});
don't forget to make your String line a member of your class, so that your Runnable has access to it...
private String line = null;
Try this..it might help
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
I'm trying to read a random line from a file. My code doesn't have error, just comes up with a force close as soon as it runs in the emulator and I can't work out why!
public class filereader extends Activity {
TextView t = (TextView)findViewById(R.id.text);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {
try {
while (s.hasNext()) {
String word = s.next();
t.setText(word);
}
}
finally {
s.close();
}
}
}
TextView t = (TextView)findViewById(R.id.text);
you can not run findViewById until the setContentView has been called:
TextView t = null; #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.text);
}
please be sure that you declare text inside the main.xml
do this
BufferedReader myReader = null;
try
{
fIn = openFileInput("customer_number.txt");
myReader = new BufferedReader(new InputStreamReader(fIn));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String aDataRow = "";
//String aBuffer = "";
try
{
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
// TO display Whole Data of File
Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();
}
// To display Last Entered Number
Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void readfromfile(){
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
String s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It will read the text file named "mytext.txt" string by string and store it by appending it to string variable s. So the variable "s" contains final string taken from file.