I have this piece of code. I am trying to read elements of the array and display it in a textview in android. The code displays the correct thing if I just use a print statement plain java instead of the android sdk. I've been trying to figure it out for a while now. Any help?
package com.example.trivia;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.Button;
import android.widget.TextView;
public class PlayActivity extends Activity {
String [][]array;
String [][] questionsArray;
int []playindexArray = new int[50];
TextView timer, questions;
Button answerA, answerB, answerC, answerD;
String show = "Buttons and Question";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
timer = (TextView) findViewById(R.id.timer);
questions = (TextView) findViewById(R.id.questions);
answerA = (Button) findViewById(R.id.buttonA);
answerB = (Button) findViewById(R.id.buttonB);
answerC = (Button) findViewById(R.id.buttonC);
answerD = (Button) findViewById(R.id.buttonD);
//countdowntimer
CountDownTimer count = new CountDownTimer(32000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("TIME REMAINING: " + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("TIME UP!");
}
};
count.start();
try {
readCSV();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readCSV() throws IOException{
array = new String[117][6];
String delimiter = ",";
int row =0;
File file = new File("questions1.csv");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
{
String line = sc.nextLine();
String [] temp = line.split(delimiter);
for(int i = 0; i< temp.length; i++){
array[row][i] = temp[i];
}
row++;
}
questionsArray = new String[117][6];
questionsArray = array;
questions.setText(questionsArray[0][2]);
}
There is no TextView in your code. Nor setText method. The simplest TextView works like this
TextView textView = (TextView) findViewById(R.id.id_of_your_textview);
text.setText("your text");
show the relevant code that you have tried first. then show the error you are getting. this will speed up the process of you getting what you are looking for.
Related
Im trying to trigger an event when i return to an activity hitting the back button.
what i want to do is when i go back with the backbutton reload some items. Is there any way to do this?
here is my Main Activity where i want to do the "reload" of data, Some thing like "onResume" or "onReEnter"
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ActivityTemporadaJson extends AppCompatActivity {
private String Nombre;
private int IdTmdb;
private String Tipo;
private int NumeroTemp;
private DBHelper mydb;
private ProgressDialog pDialog;
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original";
private Temporada temp;
private TextView nombrePelicula;
private ImageView fotoPortada;
private TextView sinopsis;
private TextView NumEpsVal;
private TextView fechaLanzVal;
private ArrayList<Episodio> episodios;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private RecyclerAdapterEpisodio mAdapterEp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temporada_json);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent recep = this.getIntent();
episodios = new ArrayList<>();
Nombre = recep.getStringExtra("Nombre");
Tipo = recep.getStringExtra("Tipo");
IdTmdb = Integer.parseInt(recep.getStringExtra("idSerie"));
NumeroTemp = Integer.parseInt(recep.getStringExtra("NumTemp"));
this.setTitle(Nombre);
nombrePelicula = (TextView) this.findViewById(R.id.NombrePelicula);
fotoPortada = (ImageView) this.findViewById(R.id.FotoPortada);
sinopsis = (TextView) this.findViewById(R.id.Sinopsis);
NumEpsVal = (TextView) this.findViewById(R.id.NumEpsVal);
fechaLanzVal = (TextView) this.findViewById(R.id.FechaLanzVal);
recyclerView = (RecyclerView) this.findViewById(R.id.recyclerviewEpisodios);
mydb = new DBHelper(this);
if (Tipo.equalsIgnoreCase("SQL")) {
Cursor res = mydb.getResultQuery("SELECT count(e.Visto) as numVisto FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp + " and e.visto = 1");
res.moveToFirst();
int NumVisto = res.getInt(0);
mydb.UpdateEpsVistos(NumVisto, IdTmdb, NumeroTemp);
TextView NumEpsVis = (TextView) this.findViewById(R.id.EpsVis);
TextView NumEpsVisVal = (TextView) this.findViewById(R.id.EpsVisVal);
NumEpsVis.setVisibility(View.VISIBLE);
NumEpsVisVal.setVisibility(View.VISIBLE);
AQuery androidAQuery = new AQuery(this);
res = mydb.getResultQuery("SELECT Nombre, Sinopsis, FechaInicio, Poster, NumeroEpisodios,EpisodiosVistos FROM Temporada WHERE IdTMDB = " + IdTmdb + " and NumeroTemporada = " + NumeroTemp);
res.moveToFirst();
nombrePelicula.setText(res.getString(0));
sinopsis.setText(res.getString(1));
fechaLanzVal.setText(res.getString(2));
androidAQuery.id(fotoPortada).image(res.getString(3), true, true, 150, 0);
NumEpsVal.setText(Integer.toString(res.getInt(4)));
NumEpsVisVal.setText(Integer.toString(res.getInt(5)));
Cursor resEps = mydb.getResultQuery("SELECT e.Nombre, e.NumeroEpisodio, e.NumeroTemporada, e.FechaEmision, e.Sinopsis, e.Poster, e.Visto, e.IdEpisodio FROM Episodio e, Temporada t WHERE t.IdTMDB = " + IdTmdb + " and e.IdTemporada = t.IdTemporada and e.NumeroTemporada = " + NumeroTemp);
resEps.moveToFirst();
while (resEps.isAfterLast() == false) {
boolean visto = false;
if (resEps.getInt(6) == 1) {
visto = true;
}
Episodio nuevo = new Episodio(resEps.getInt(7), 0, resEps.getString(0), resEps.getInt(1), resEps.getInt(2), resEps.getString(3), resEps.getString(4), resEps.getString(5), visto);
episodios.add(nuevo);
resEps.moveToNext();
}
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(episodios, IdTmdb, Tipo);
recyclerView.setAdapter(mAdapterEp);
} else {
new GetTemp(this).execute();
}
//mydb = new DBHelper(this);
}
private class GetTemp extends AsyncTask<Void, Void, Void> {
Context c;
public GetTemp(Context c)
{
this.c = c;
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
//https://api.themoviedb.org/3/tv/57243/season/1?api_key=5e2780b2117b40f9e4dfb96572a7bc4d&language=en-US
String url = "https://api.themoviedb.org/3/tv/"+IdTmdb+"/season/"+NumeroTemp+"?api_key="+API+"&language=es-ES";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray episodes = jsonObj.getJSONArray("episodes");
String fecha = jsonObj.getString("air_date");
String nombreSerie = jsonObj.getString("name");
int numEps = episodes.length();
int numTemp = jsonObj.getInt("season_number");
String sinop = jsonObj.getString("overview");
String poster =URLFOTO + jsonObj.getString("poster_path");
// looping through All Contacts
for (int i = 0; i < episodes.length(); i++) {
JSONObject c = episodes.getJSONObject(i);
Episodio nuevo = new Episodio();
nuevo.setSinopsis(c.getString("overview"));
nuevo.setFechaEmision(c.getString("air_date"));
nuevo.setNombreEpisodio(c.getString("name"));
nuevo.setNumeroEpisodio(c.getInt("episode_number"));
nuevo.setNumeroTemporada(c.getInt("season_number"));
nuevo.setPoster(URLFOTO + c.getString("still_path"));
episodios.add(nuevo);
}
temp = new Temporada(0, IdTmdb, nombreSerie, sinop, fecha, poster, numTemp,false, 0, numEps, episodios);
} catch (final JSONException e) {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AQuery androidAQuery=new AQuery(c);
// Dismiss the progress dialog
if (pDialog.isShowing())
{
pDialog.dismiss();
}
androidAQuery.id(fotoPortada).image(temp.getPoster(), true, true, 150,0);
String Nombre = "Temporada " + temp.getNumeroTemporada();
nombrePelicula.setText(Nombre);
sinopsis.setText(temp.getSinopsis());
NumEpsVal.setText(Integer.toString(temp.getNumeroEpisodios()));
fechaLanzVal.setText(temp.getFechaInicio());
mLinearLayoutManager = new LinearLayoutManager(c, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterEp = new RecyclerAdapterEpisodio(temp.getEpisodios(),IdTmdb,Tipo);
recyclerView.setAdapter(mAdapterEp);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(c);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
}
You can use onRestart , which will be triggered when existing activity will be bought back to front .
As quoted in docs
Called after onStop() when the current activity is being re-displayed
to the user (the user has navigated back to it). It will be followed
by onStart() and then onResume().
so Override onRestart
#Override
public void onRestart() {
// you come back to me
}
I am working on app which communicate the web server. I want two methods which call by thread and also need two handler method, which used to update UI . 1 thread method and handler method need to fetch data and update UI at start of the activity. 2 thread method and handler method need to post back data on server.
How I implement this.
My code of this class...
package com.edoc.doctor;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.edoc.libraries.FetchMedicines;
import com.edoc.libraries.Functions;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class AddPatient extends Activity implements Runnable, OnClickListener
{
public static final String appDoctor = "AppDoctor";
public String KEY_SUCCESS = "success";
private String success;
private ProgressDialog pd;
private JSONObject jsonObj;
private boolean addNewPatient;
private EditText email;
private EditText phone;
private EditText name;
private EditText dob;
private EditText lowBPMedicineInstructions;
private EditText highBPMedicineInstructions;
private EditText hyperLowBPMedicineInstructions;
private EditText hyperHighBPMedicineInstructions;
private Spinner lowBPMedicine;
private Spinner highBPMedicine;
private Spinner hyperLowBPMedicine;
private Spinner hyperHighBPMedicine;
private Button addPatient;
private String strEmail;
private String strPhone;
private String strName;
private String strDob;
private String strLowBPMedicineInstructions;
private String strHighBPMedicineInstructions;
private String strHyperLowBPMedicineInstructions;
private String strHyperHighBPMedicineInstructions;
private String strLowBPMedicine;
private String strHighBPMedicine;
private String strHyperLowBPMedicine;
private String strHyperHighBPMedicine;
private ArrayAdapter<String> dataAdapter;
private ArrayList<String> medicines;
private ArrayList<Integer> medicineIDs;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_patient);
medicines = new ArrayList<String>();
medicineIDs = new ArrayList<Integer>();
addPatient = (Button) findViewById(R.id.ib_add_patient);
addPatient.setOnClickListener(this);
email = (EditText) findViewById(R.id.iet_add_patient_email);
phone = (EditText) findViewById(R.id.iet_add_patient_phone);
name = (EditText) findViewById(R.id.iet_add_patient_name);
dob = (EditText) findViewById(R.id.iet_add_patient_date_of_birth);
lowBPMedicineInstructions = (EditText) findViewById(R.id.iet_low_description);
highBPMedicineInstructions = (EditText) findViewById(R.id.iet_high_description);
hyperLowBPMedicineInstructions = (EditText) findViewById(R.id.iet_hyper_low_description);
hyperHighBPMedicineInstructions = (EditText) findViewById(R.id.iet_hyper_high_description);
lowBPMedicine = (Spinner) findViewById(R.id.isp_low_medicine);
highBPMedicine = (Spinner) findViewById(R.id.high_medicine);
hyperLowBPMedicine = (Spinner) findViewById(R.id.hyper_low_medicine);
hyperHighBPMedicine = (Spinner) findViewById(R.id.hyper_high_medicine);
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, medicines);
final int did = getID();
// pd = ProgressDialog.show(getApplicationContext(), "Working..", "Connect To Server", true,false);
new Thread(new Runnable()
{
public void run()
{
Functions fun = new Functions();
jsonObj = fun.fetchMedicines(did);
handler.sendEmptyMessage(0);
}
}).start();
}
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
try {
Log.e("try","try");
success = jsonObj.getString("success");
Log.e("success",success);
Log.e("add",""+addNewPatient);
if(success.equals("1") && !addNewPatient)
{
JSONArray m = jsonObj.getJSONArray("medicines");
// looping through All Contacts
for(int i = 0; i < m.length(); i++)
{
JSONObject c = m.getJSONObject(i);
String name = c.getString("medicine");
int id = c.getInt("id");
Log.e("m name",name+" "+id);
medicines.add(name);
medicineIDs.add(id);
}
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lowBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
highBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hyperLowBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hyperHighBPMedicine.setAdapter(dataAdapter);
}
else if(success.equals("1") && addNewPatient)
{
Log.e("success", ""+addNewPatient);
pd.dismiss();
Toast.makeText(getApplicationContext(), "Patient Add Successfully",Toast.LENGTH_LONG).show();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Server down",Toast.LENGTH_LONG).show();
finish();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public int getID()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(appDoctor,mode);
Editor editor = mySharedPreferences.edit();
return mySharedPreferences.getInt("id",0);
}
#Override
public void run()
{
Functions function = new Functions();
jsonObj = function.addPatient(strEmail,strPhone,strName,strDob,strLowBPMedicine
,strHighBPMedicine,strHyperHighBPMedicine,strHyperLowBPMedicine,strLowBPMedicineInstructions
, strHighBPMedicineInstructions, strHyperLowBPMedicineInstructions, strHyperHighBPMedicineInstructions, getID());
addNewPatient = true;
Log.e("run", ""+addNewPatient);
handler.sendEmptyMessage(0);
}
#Override
public void onClick(View v)
{
Log.e("onclick","on click");
strEmail = email.getText().toString();
strPhone = phone.getText().toString();
strName = name.getText().toString();
strDob = dob.getText().toString();
strLowBPMedicine = ""+lowBPMedicine.getSelectedItemPosition();
strHighBPMedicine = ""+highBPMedicine.getSelectedItemPosition();
strHyperLowBPMedicine = ""+hyperLowBPMedicine.getSelectedItemPosition();
strHyperLowBPMedicine = ""+hyperLowBPMedicine.getSelectedItemPosition();
strLowBPMedicineInstructions = lowBPMedicineInstructions.getText().toString();
strHighBPMedicineInstructions = highBPMedicineInstructions.getText().toString();
strHyperLowBPMedicineInstructions = hyperLowBPMedicineInstructions.getText().toString();
strHyperHighBPMedicineInstructions = hyperHighBPMedicineInstructions.getText().toString();
pd = ProgressDialog.show(this, "Working..", "Connect To Server", true,false);
Thread t = new Thread();
t.start();
}
}
This stuck on line 222
form below 3rd statement.
pd = ProgressDialog.show(this, "Working..", "Connect To Server", true,false);
I am developing an application in which i need to read a resource file. I am saving my file (named "sample")in raw directory of res folder. When i tried to access it in code, by writing its resource id as R.raw.sample , it gives the following error.
Error(30,60)Cannot find symbol variable raw.
I am using intellij idea 11.0.3 and platform for android is 2.3.3.
The code is as follows...
package com.example;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SampleLoader {
public SampleLoader(){
}
public static int[] readFromFile(Context ctx, int resId){
String sample = readRawTextFile(ctx,resId);
int [] arr = stringToIntArray(sample);
return arr;
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader buffReader = new BufferedReader(inputReader);
String line;
StringBuilder text = new StringBuilder();
try {
//while (( line = buffReader.readLine()) != null) {
if (( line = buffReader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
public static int[] stringToIntArray(String line){
int[] sample = new int[line.length()-2];
String s ;
for (int i=0; i<line.length(); i++)
{
if(i>1)
{ sample[i] = Character.getNumericValue(line.charAt(i));
}
}
return sample;
}
public void populateListOfSamples(){
}
}
package com.example;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(createContent());
}
LinearLayout createContent(){
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
linearLayout.setLayoutParams(params);
final int[] arr6 = SampleLoader.readFromFile(this,R.raw.sample) ;
final Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.no3);
final ImageView imageView1 = new ImageView(this);
imageView1.setVisibility(View.INVISIBLE);
final TextView textView = new TextView(this);
String str2 = "Byte Array will appear here!";
textView.setText(str2);
final Button btn2 = new Button(this);
final Button btn = new Button(this);
btn.setText("Convert Pic to Byte Array");
btn.setOnClickListener(new View.OnClickListener() { //Event handler for click event.
public void onClick(View v) {
textView.setText(str3);
btn2.setVisibility(View.VISIBLE);
}
});
btn2.setText("Convert Byte Array to Pic");
btn2.setVisibility(View.INVISIBLE);
btn2.setOnClickListener(new View.OnClickListener() { //Event handler for click event.
public void onClick(View v) {
btn.setVisibility(View.INVISIBLE);
final Bitmap imag = filing.arrtoimg(arr6);
textView.setVisibility(View.INVISIBLE);
imageView1.setVisibility(View.VISIBLE);
imageView1.setImageBitmap(imag);
}
});
linearLayout.addView(imageView1);
linearLayout.addView(btn);
linearLayout.addView(btn2);
linearLayout.addView(textView);
return linearLayout;
}
}
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.
I have an Activity that retrieves information from a url. I have 2 textviews which are multi-line (txtTitle & txtContent). If I populate them without using thread, it displays as multi-line. However, when I use a thread, the text views become single-line.
Is there anything I'm missing? Is the UI not completely ready when I tried putting text in it?
My sample code is below:
package com.mysite.app;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;
public class ViewNewsActivity extends Activity implements Runnable{
private ProgressDialog progressDialog = null;
private String apiUrl = "";
private String title = "";
private String content = "";
private Runnable viewNews;
private TextView txtTitle = null;
private TextView txtContent = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_news);
Intent myIntent = getIntent();
apiUrl = "http://www.mysite.com" + myIntent.getStringExtra("api_url");
Thread thread = new Thread(this);
thread.start();
progressDialog = ProgressDialog.show(ViewNewsActivity.this,
"Please wait...", "Retrieving News ...", true);
}
public void run() {
txtTitle = (TextView)findViewById(R.id.view_news_title);
txtContent = (TextView)findViewById(R.id.view_news_content);
getNews(apiUrl);
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
txtTitle.setText(title);
Spanned contentHtml = Html.fromHtml(content);
txtContent.setText(contentHtml.toString());
}
};
private void getNews(String apiUrl) {
String result = JSONUtils.getJSONResponse(apiUrl);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);
title = jsonResponse.getString("title");
content = jsonResponse.getString("content");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}