I have the following main class and thread-TCP Client. The client runs in a loop, receives messages and passes it to main class. In the main class, I parse the message and try to show different images based on the name and value of the message received.
Ex: shiftDirection1
name: shiftDirection & value: 1
But I can show only the image corresponding to the first received message and the images corresponding to the remaining received messages cannot be displayed.
Please go through the code below and kindly suggest the mistake/problem and alternative ways.
Thank you for your time and efforts.
Madhu
main class:
public class TCPListen extends Activity implements TCPListener {
private TextView mTitle;
public String recData[] = new String[2];
String PresentGear = "0";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TcpServiceHandler handler = new TcpServiceHandler(this,this);
Thread th = new Thread(handler);
th.start();
}
public String[] callCompleted(String source){
//Log.d("TCP", "Std parser " + source);
//mTitle.setText(source);
//String data[] = new String[2];
//if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>")) {
Document doc = null;
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes()));
NodeList n = doc.getElementsByTagName("N");
Node nd = n.item(0);
String msgName = nd.getFirstChild().getNodeValue();
NodeList n1 = doc.getElementsByTagName("V");
Node nd1 = n1.item(0);
String tmpVal = nd1.getFirstChild().getNodeValue();
recData[0] = msgName;
recData[1] = tmpVal;
if (recData[0].equals("currGear")) PresentGear = recData[1];
Log.d("TCP", "Inside Std parser " + recData[0] + " " + recData[1]);
actionOnData(recData[0], recData[1]);
}
catch(Exception e){
e.printStackTrace();
}
Log.d("TCP", "Just outside Std parser " + recData[0] + " " + recData[1]);
return recData;
//} else Log.d("TCP", "Message in wrong format " + source);
//mTitle.setText("Message in wrong format " + source);
//return data;
}
//Function to display driver messages/images based on individual messages
public void actionOnData(String name, String value) {
String tempName = name;
String tempVal = value;
setContentView(R.layout.image);
ImageView showImage = (ImageView) findViewById(R.id.imageView1);
//Log.d("TCP", "------------>" + tempName + " " + tempVal);
if (tempName.equals("shiftDirection") && tempVal.equals("1")) {
//setContentView(R.layout.image);
//TextView text_top = (TextView) findViewById(R.id.textView1);
//showImage = (ImageView) findViewById(R.id.imageView1);
//text_bottom.setText(Info[1]);
showImage.setImageResource(R.drawable.shift_up);
Log.d("TCP", "1------------>" + showImage);
} else if (tempName.equals("shiftDirection") && tempVal.equals("-1")) {
//setContentView(R.layout.image);
//TextView text_bottom = (TextView) findViewById(R.id.textView2);
//Resources res = getResources();
//Drawable drawable = res.getDrawable(R.drawable.shift_down);
//showImage = (ImageView) findViewById(R.id.imageView1);
//text_bottom.setText(Info[1]);
showImage.setImageResource(R.drawable.shift_down);
} else if (tempName.equals("recomGear") && tempVal != null) {
Log.d("TCP", "3------------>" + tempName + " " + tempVal);
Integer msgValue = Integer.parseInt(recData[1]);
//Integer CurrentGear = (msgValue) - 1;
//Log.d("TCP","in DA Images. Current gear: " + CurrentGear);
//String Gear = Integer.toString(CurrentGear);
setContentView(R.layout.image);
TextView text_top = (TextView) findViewById(R.id.textView1);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
showImage = (ImageView) findViewById(R.id.imageView1);
showImage.setImageResource(R.drawable.shift_up);
text_bottom.setText(PresentGear);
text_top.setText(tempVal);
} else if (tempName.equals("currGear") && tempVal != null) {
Log.d("TCP", "4------------>" + tempName + " " + tempVal);
PresentGear = tempVal;
//Log.d("TCP","in DA Images. Present gear1: " + PresentGear);
setContentView(R.layout.image);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
text_bottom.setText(PresentGear);
} else if (tempName.equals("shiftDirection") && tempVal.equals("0")) {
Log.d("TCP", "5------------>" + tempName + " " + tempVal);
Log.d("TCP","in DA Images. Present gear: " + PresentGear);
setContentView(R.layout.image);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
//TextView text_top = (TextView) findViewById(R.id.textView1);
//text_top.setText("Go on");
text_bottom.setText(PresentGear);
}
}
}
Only the image corresponding to the first if case is displayed. The program control enters the second if loop but does not show the image there.
Interface:
public interface TCPListener {
public String[] callCompleted(String msg);
}
Thread (TCP Client):
public class TcpServiceHandler implements Runnable {
TCPListener _listener;
private Activity _act;
public BufferedReader in;
public TcpServiceHandler(TCPListener listener, Activity act){
_listener = listener;
_act = act;
}
public synchronized void run() {
// TODO Auto-generated method stub
//if(socket==null){
try {
//InetAddress serverAddr = InetAddress.getByName("192.168.178.25");
Socket socket = new Socket("192.168.62.23", 1200, true);
//
//while(true){
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final int delay = 100;
final Timer _timer = new Timer();
_timer.scheduleAtFixedRate(new TimerTask() {
public void run(){
String str;
try {
str = in.readLine();
_listener.callCompleted(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, delay);
//final String str = in.readLine();
//this._act.runOnUiThread(new Runnable(){
//public void run() {
// _listener.callCompleted(str);
// }
//});
}
catch(Exception e){
e.printStackTrace();
}
//}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You might check 2 things:
Your TcpServiceHandler is a Runnable of a thread but there is no loop in run(). The _timer you define inside this method might be dead and gone before it's work is done.
Are you changing the UI from a background thread? This is not a good idea in general.
Check AsyncTask which is a handy tool to run operations in the background.
Related
I'am a beginner in android and i use AndroidStudio
I have a problem
in have 2 class i my project in the first class "fetch compte" i fill my table "dataParsed" and i 'am certain that the table is fil
but in the second class MainActivity
I find that the table is empty
please help me
this is my code
public class fetchcompte extends AsyncTask<Void,Void,Void> {
String data = "";
String dat = "";
public static String[] dataParsed ;
String singleParsed ;
String dataParse = "";
String singleParse1 = "";
String singleParse2 = "";
String singleParse3 = "";
String singleParse4 = "";
String singleParse5 = "";
private RequestQueue mQueue, mQueu;
int nbcompte;
protected Void doInBackground(Void... voids) {
String S = jsonArray;
// singleParsed=new String[20];
dataParsed=new String[20];
try {
// String url2="http://recrutement.stb.com.tn:1010/PlateformeApi_Externe/api/ComptesClient/000001498675\n";
//String url2 = "http://10.1.11.168:8081/my/banks/10/accounts/10403082500589678844/transactions";
String url2 = "http://10.12.0.66:8081/api/ComptesClient/000001498675";
URL url = new URL(url2);
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);
nbcompte=JA.length();
for(int i =0 ;i<nbcompte; i++) {
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "fullname:" + JO.get("fullname");
singleParse1 = "accountnumber:" + JO.get("accountnumber");
singleParse2 = "rib:" + JO.get("rib");
singleParse3 = "iban:" + JO.get("iban");
singleParse4 = "name:" + JO.get("name");
singleParse5 = "balance:" + JO.get("balance");
dataParsed[i] = singleParsed + "\n" + singleParse1 + "\n" + singleParse2 + "\n" + singleParse3 + "\n" + singleParse4 + "\n" + singleParse5;
}
// dataParsed[i] =dataParsed[i] +singleParsed[i] +"\n" ;
// MainActivity.compte[i]=dataParsed[i];
// singleParsed[i] = "fullname:" + JO.get("fullname") + "\n"+
// "accountnumber:" + JO.get("accountnumber") + "\n"+
// "rib:" + JO.get("rib") + "\n"+
// "iban:" + JO.get("iban") + "\n"+
// "name:" + JO.get("name") + "\n"+
//"balance:" + JO.get("balance") + "\n";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
for(int i =0 ;i <2; i++) {
// MainActivity.data.setText(this.d[i]);
}
}
//Authorization Bearer
my MainActivity
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
public static String jsonArray;
private RequestQueue mQueue;
ImageView imageView2;
public static TextView textView_type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQueue = Volley.newRequestQueue(this);
click = (Button) findViewById(R.id.button_parse);
data = (TextView) findViewById(R.id.text_view_result);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.listeview);
CustomAdaptercompte customAdapter=new CustomAdaptercompte();
ListView listeview=(ListView) findViewById(R.id.liste);
listeview.setAdapter(customAdapter);
fetchcompte process = new fetchcompte();
process.execute();
}
});
}
public class CustomAdaptercompte extends BaseAdapter {
#Override
public int getCount() {
return 2;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewgrp) {
View view = getLayoutInflater().inflate(R.layout.customlayout,null);
imageView2 = (ImageView) view.findViewById(R.id.imageView2);
textView_type =(TextView) view.findViewById(R.id.textView_type);
imageView2.setImageResource(R.drawable.compte);
textView_type.setText(dataParsed[i]);
return view;
}
}
}
The mistake that you have made is that you assume that
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
will automatically just be the dataParsed Variable you need. What that line does is that it gets the default value of dataParsed (from a default fetchcompte instance). Since you make another instance of a fetchcompte object [called process] (which you are using to populate its dataParsed variable) simply access the dataParsed variable of that instance.
So instead of using:
textView_type.setText(dataParsed[i]);
You can use:
textView_type.setText(process.dataParsed[i]);
But to do this you will need to somehow access the process variable in your adapter class.
enter image description herehow can i add multiple TextView and their inside relative layout dynamically which is already created? Also I have to call the values of those text boxes from database sqlite.
public class DownloadPackagesActivity extends Activity implements AdapterView.OnItemSelectedListener{
private SQLiteDatabase db;
DBHelper dbHelper;
String newFolder = "";
int SId = 1;
TextView subjects;
List<String> categories = new ArrayList<String>();
String FilePart = "";
DownloadManager dManager;
long did;
// private static String file_url = "http://mobileteacher.in/audio/demo/2725.mp3";
String urlString ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_packages);
// Get DownloadManager instance
dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
subjects = (TextView)findViewById(R.id.subjects);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinnerPackage);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Add textview
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery("select * from DownloadSubject", null);
while (c.moveToNext()) {
categories.add(c.getString(1));
}
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, categories);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setAdapter(dataAdapter1);
showPart();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SId = position + 1;
showPart();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void showPart()
{
int j=1;
int ii=0;
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
TableLayout stk = (TableLayout) findViewById(R.id.tbl);
stk.removeAllViews();
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c;
if (SId==8 || SId==9)
{
c = db.rawQuery("select * from DownloadSubject", null);
}
else
{
c = db.rawQuery("select * from DownloadSubject where Id = '"+ SId +"'", null);
}
while (c.moveToNext())
{
subjects.clearComposingText();
String[] part = c.getString(2).split(",");
for(int i = 0;i<part.length;i++)
{
TableRow tr1 = new TableRow(this);
Button button = new Button(this);
button.setBackgroundColor(Color.TRANSPARENT);
button.setText(part[i] +"\u00A0 \u00A0 \u00A0 \u00A0 Download");
button.setTextColor(Color.BLUE);
button.setPadding(20, 0, 0, 0);
button.setOnClickListener(downloads());
button.setId(i);
// button.setHint(part[i]);
tr1.addView(button);
stk.addView(tr1);
}
stk = (TableLayout) findViewById(R.id.tbl);
int N = 1;
TextView[] TextViews = new TextView[N]; // create an empty array;
// for (int i = 0; i < N; i++) {
//if(ii!=0) {
// subjects.setText(c.getString(j));
// Toast.makeText(this, c.getString(j), Toast.LENGTH_LONG).show();
// save a reference to the textview for later
// TextViews[j] = TextView;
//}
if(ii==0)
{
subjects.setText(c.getString(j));
ii=ii+1;
}
else
{
final TextView TextView = new TextView(this);
TextView.setText(c.getString(j));
TextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TextView.setPadding(0, 20, 0, 20);
TextView.setTextSize(getResources().getDimension(R.dimen.textsize));
TextView.setTextColor(Color.parseColor("#800080"));
// add the textview to the layout
stk.addView(TextView);
}
}
}
public String part;
View.OnClickListener downloads()
{
return new View.OnClickListener()
{
public void onClick(View v) {
//Button b1 = (Button)v;
//int i = b1.getId();
// Toast.makeText(getApplicationContext(),"Ide = " + i,Toast.LENGTH_LONG).show();
part ="";
TextView subjects = (TextView)findViewById(R.id.subjects);
if(subjects.getText().toString().equals("Modern History (500 MB)"))
{
part = "modern_history";
}
else if(subjects.getText().toString().equals("Polity (250 MB)"))
{
part = "polity";
}
else if(subjects.getText().toString().equals("Economy (100 MB)"))
{
part = "economy";
}
else if(subjects.getText().toString().equals("Ancient History (500 MB)"))
{
part = "ancient_history";
}
else if(subjects.getText().toString().equals("English Grammar (500 MB)"))
{
part = "english_grammar";
}
else if(subjects.getText().toString().equals("Vocabulary (560 MB)"))
{
part = "vocabulary";
}
else if(subjects.getText().toString().equals("Maths (100 MB)"))
{
part = "maths";
}
else if(subjects.getText().toString().equals("One Day Complete(Vol.1(2GB))"))
{
part = "oneday_complete";
}
else if(subjects.getText().toString().equals("Civil Complete (Vol.1 (2GB))"))
{
part = "civil_complete" ;
}
newFolder = "/voice";
subjects = (TextView)findViewById(R.id.subjects);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
//File f = new File(myNewFolder);
myNewFolder.mkdir();
Button b = (Button)v;
FilePart = b.getText().toString();
String RemoveSpace = FilePart.split("\u00A0")[0].replace(" ","");
try {
urlString = "http://mobileteacher.in/DealerPackage/" + part + "/" + RemoveSpace + ".zip";
downloadFile();
Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Please Connect Internet", Toast.LENGTH_LONG).show();
}
}
};
}
public void downloadFile() {
// String urlString = "http://mobileteacher.in/audio/demo/2725.mp3";
if (!urlString.equals("")) {
try {
// Get file name from the url
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
// Create Download Request object
DownloadManager.Request request = new DownloadManager.Request(Uri.parse((urlString)));
// Display download progress and status message in notification bar
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Set description to display in notification
// request.setDescription("Download " + fileName + " from " + urlString);
request.setDescription("Download " + fileName + " from mobileteacher.in");
// Set title
request.setTitle("Mobile Teacher");
// Set destination location for the downloaded file
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/voice/"+fileName.split("\u00A0")[0].replace(" ","")));
// Download the file if the Download manager is ready
did = dManager.enqueue(request);
} catch (Exception e) {
}
}
}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(did);
Cursor cursor = dManager.query(q);
if (cursor.moveToFirst()) {
String message = "";
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
message = "Download successful";
} else if (status == DownloadManager.STATUS_FAILED) {
message = "Download failed";
}
//query.setText(message);
}
}
};
protected void onResume() {
super.onResume();
// Register the receiver to receive an intent when download complete
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Unregister the receiver
unregisterReceiver(downloadReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_download_packages, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void back(View view)
{
finish();
}
public void Create(View view)
{
String newFolder = "/voice";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(ext[enter image description here][1]StorageDirectory + newFolder);
myNewFolder.mkdir();
}
}
this is the image
create relative layout object from it layout id, then you can add it as below
relativeLayout = findViewById(R.id.yourRelativeLayoutId);
relativeLayout.addView(yourView);
Listview or recyclerview is best for practice but as you want to use textview, you can use like this in your code:
RelativeLayout relativeLayout =
(RelativeLayout) findViewById(R.id.rootlayout);
TextView textView = new TextView(this);
textView.setText("Hey, I am TextView");
relativeLayout.addView(textView);
appending a textview to relativelayout is pretty simple.
just use
TextView textview = new TextView(this);
textview.setText("Text");
relativelayoutobject.addView(textview);
to setup the position use
textview.setLayoutParams(thelayoutparams)
But if you use big database, please, use 'TableLayout' instead of your method due to performance reasons.
Define relative layout in your xml layout. Add multiple textview programmatic ally like this-
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
//use a for loop to define multiple textView in RelativeLayout
//length is no. of textView you required
for (int i = 0; i < length; i++) {
TextView tv = new TextView(relativeLayout.getContext());
tv.setText("Text from sqlite database");
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(tv);
}
i would like to display an image based on the weather.
The image that I'm getting from is from drawable.
For example :
if the code = 30, it will display rainy day icon
I'm retrieving it from
<yweather:condition text="Light Rain with Thunder" code="4" temp="25" date="Thu, 18 Jul 2013 7:58 am SGT" />
Here is my code
MainActivity.java
public class MainActivity extends Activity {
TextView weather;
ImageView image;
class MyWeather{
String conditiontext;
String conditiondate;
String numberOfForecast;
String forecast;
public String toString(){
return "\n- "
+ "Weather:" + image + "\n"
+ "Condition: " + conditiontext + "\n"
+ conditiondate +"\n"
+ "\n"
+ "number of forecast: " + numberOfForecast + "\n"
+ forecast;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weather = (TextView)findViewById(R.id.weather);
image = (ImageView)findViewById(R.id.image);
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.toString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
if(conditionNode.getTextContent().equals("11")){
image.setImageResource(R.drawable.logo);
}
else {
image.setImageResource(R.drawable.old);
}
myWeather.conditiontext = conditionNode.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString();
myWeather.conditiondate = conditionNode.getAttributes()
.getNamedItem("date")
.getNodeValue()
.toString();
//Added to get elements of <yweather:forecast.../>
NodeList forecastList = srcDoc.getElementsByTagName("yweather:forecast");
myWeather.forecast = "";
if(forecastList.getLength() > 0){
myWeather.numberOfForecast = String.valueOf(forecastList.getLength());
for(int i = 0; i < forecastList.getLength(); i++){
Node forecastNode = forecastList.item(i);
myWeather.forecast +=
forecastNode
.getAttributes()
.getNamedItem("date")
.getNodeValue()
.toString() + " " +
forecastNode
.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString() +
" High: " + forecastNode
.getAttributes()
.getNamedItem("high")
.getNodeValue()
.toString() +
" Low: " + forecastNode
.getAttributes()
.getNamedItem("low")
.getNodeValue()
.toString() + "\n";
}
}else{
myWeather.numberOfForecast = "No forecast";
}
return myWeather;
}
private Document convertStringToDocument(String src){
Document dest = null;
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(MainActivity.this,
e1.toString(), Toast.LENGTH_LONG).show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return dest;
}
private String QueryYahooWeather(){
String qResult = "";
String queryString = "http://weather.yahooapis.com/forecastrss?w=1062617&u=c";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(queryString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return qResult;
}
}
Still not working?
I made the project myself, and if you do it like this it will work. :)
The R.id and drawables are not the same, you need to change those to make it work
TextView weather;
ImageView forecast;
private static Handler mHandler = new Handler();
class MyWeather{
String conditiontext;
String conditiondate;
String numberOfForecast;
String forecast;
public String forecastToString(){
return "\n- "
+ "Weather: " +"you wanted to have something here, I just dont understand what. " + "\n"
+ "Condition: " + conditiontext + "\n"
+ conditiondate +"\n"
+ "\n"
+ "number of forecast: " + numberOfForecast + "\n"
+ forecast;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weather = (TextView)findViewById(R.id.textView1);
forecast = (ImageView)findViewById(R.id.imageView1);
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.forecastToString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
String weatherCode = conditionNode.getAttributes()
.getNamedItem("code")
.getNodeValue()
.toString();
if(weatherCode.equals("28")){
mHandler.post(new Runnable() {
#Override
public void run() {
// This gets executed on the UI thread so it can safely modify
// Views
forecast.setImageResource(R.drawable.ic_launcher);
}
});
}
...
I found some problem in your code there is two image view
Image = (ImageView)findViewById(R.id.image);
Problem - : name of the image missing
ImageView foreImage = new ImageView(this);
foreImage.setImageResource(R.drawable.logo);
//Why are you using dynamic imageview
You should use Handler Thread for display image.
I have a custom Listview with on every item an imagebutton that should give me directions to a building. When pressing the DirectionsButtons, google maps opens up but the coordinations are filled in wrong.
To destination it gives me just a comma. Can someone help me track down what I'm doing wrong?
public class buildingList extends Activity {
String myLat = "";
String myLng = "";
private List<buildingObject> buildingItem = new ArrayList<buildingObject>();
ViewHolder holder = new ViewHolder();
ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLocations();
setContentView(R.layout.building_list);
new GetbuildingsTask().execute(myLat, myLng);
}
private void populateListview() {
ArrayAdapter<buildingObject> adapter = new MyListAdapter();
list = (ListView) findViewById(R.id.buildingList);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<buildingObject> {
public MyListAdapter() {
super(buildingList.this, R.layout.building_row, buildingItem);
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
//Null possible, so checking
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.building_row, parent, false);
}
// Find the item to work with
buildingObject currentItem = buildingItem.get(position);
// Filling the View
holder.thumbnail = (ImageButton) itemView.findViewById(R.id.btnbuildingListThumbnail);
holder.thumbnail.setBackgroundResource(currentItem.getThumbnail());
holder.name = (TextView) itemView.findViewById(R.id.lblbuildingListItemName);
holder.name.setText(currentItem.getName());
holder.btnDirections = (ImageButton) itemView.findViewById(R.id.btnbuildingListDirections);
holder.thumbnail = (ImageButton) itemView.findViewById(R.id.btnbuildingListThumbnail);
holder.btnShare = (ImageButton) itemView.findViewById(R.id.btnbuildingListShare);
holder.btnDirections.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView txtLat = (TextView) parent.getChildAt(position - list.getFirstVisiblePosition()).findViewById(R.id.lblbuildingListlatitude);
TextView txtLng = (TextView) parent.getChildAt(position - list.getFirstVisiblePosition()).findViewById(R.id.lblbuildingListlongitude);
String lat = txtLat.getText().toString();
String lng = txtLng.getText().toString();
Log.v("Lat ", "Lat of selected building is " + lat);
Log.v("Lng ", "Lng of selected building is " + lng);
Uri uri = Uri.parse("http://maps.google.com/maps?&saddr=" + myLat + "," + myLng + "&daddr=" + lat + "," + lng);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
holder.thumbnail.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String btnmsg = "ThumbNail";
Toast.makeText(buildingList.this, btnmsg, Toast.LENGTH_LONG).show();
}
});
holder.btnShare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String btnmsg = "Share";
Toast.makeText(buildingList.this, btnmsg, Toast.LENGTH_LONG).show();
}
});
return itemView;
}
}
static class ViewHolder {
ImageButton thumbnail;
TextView name;
ImageButton btnDirections;
ImageButton btnShare;
}
private void getLocations() {
String[] locations = getApplicationContext().fileList();
FileInputStream fis;
for (int i = 0; i < locations.length; i++) {
if (locations[i].equals("my_latitude")) {
try {
fis = openFileInput(locations[i]);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {
myLat += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (locations[i].equals("my_longitude")) {
try {
fis = openFileInput(locations[i]);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {
myLng += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class GetbuildingsTask extends AsyncTask<String, Void, JSONArray> {
#Override
protected JSONArray doInBackground(String... data) {
String lat = data[0];
String lng = data[1];
JSONParser jParser = new JSONParser();
JSONArray json = jParser
.getJSONFromUrl("http://www.mysite.eu/index.php/building/searchbuildingsJSON?lat=" + lat + "&lng=" + lng + "&radius=10");
return json;
}
protected void onPostExecute(JSONArray result) {
if (result != null) {
try {
Log.v(result.getString(0), result.getString(0));
} catch (JSONException e) {
e.printStackTrace();
}
Toast toast = Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_SHORT);
toast.show();
Log.d("whut", "" + result.length());
String[] buildings = new String[result.length()];
buildingObject[] building = new buildingObject[result.length()];
try {
for (int i = 0; i < result.length(); i++) {
JSONObject row;
row = result.getJSONObject(i);
buildings[i] = row.getString("Name");
buildings[i] += "" + row.getDouble("Latitude");
buildings[i] += "" + row.getDouble("Longitude");
buildings[i] += ". Distance: " + row.getDouble("distance") + "km";
String Name = row.getString("Name");
float lat = (float) row.getDouble("Latitude");
float lng = (float) row.getDouble("Longitude");
float dist = (float) row.getDouble("distance");
//building[i] = new buildingObject(Name, lat, lng, dist);
buildingItem.add(new buildingObject(Name,lat, lng, dist));
}
} catch (JSONException e) {
Log.v("Noooooooooooo", "You were the chosen one");
Log.e("Noooooooooooo", "Dis iz die erreur: " + e.toString());
}
populateListview();
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Please enable internet", Toast.LENGTH_LONG);
toast.show();
}
}
}
}
Your code seems fine.
Have you set a debug point at:
Uri uri = Uri.parse("http://maps.google.com/maps?&saddr=" + myLat + "," + myLng + "&daddr=" + lat + "," + lng)
My guess is that myLat and myLng are empty, thus leaving only a "," (comma).
If it is in fact empty or null, then the next spot I would put a debug point is at (or just before):
myLat += new String(input);
and
myLng += new String(input);
Is this ever being hit? Is an Exception thrown instead?
EDIT
Around here:
// Filling the View
Where are you populating the lblbuildingListlatitude and long text views?
I am trying to reverse geocode inside an AsyncTask to get the address of the current location. I want to set the EditText to the address as default when starting the activity. My problem is I am unable to do this in onPostExecute(), however, I can do it in runOnUiThread() inside doInBackground(). Why is this?
AsyncTask:
protected String doInBackground(Void ...params) {
Geocoder geocoder = new Geocoder(AddSpot.this, Locale.getDefault());
List<Address> addresses = null;
try {
// Call the synchronous getFromLocation() method by passing in the lat/long values.
addresses = geocoder.getFromLocation(currentLat, currentLng, 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
final String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
System.out.println(addressText);
return addressText;
}
return null;
}
protected void onPostExecute(String address) {
EditText addrField=(EditText)findViewById(R.id.addr);
addrField.setText(address);
}
That does not work. However, when I stick a runOnUiThread in it, it works:
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
final String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
runOnUiThread(new Runnable()
{
#Override
public void run()
{
EditText addrField=(EditText)findViewById(R.id.addr);
addrField.setText(addressText);
}
});
System.out.println(addressText);
return addressText;
}
UPDATE
After some debugging it appears that onPostExecute is never called at all no matter what I do.
Things I have tried:
Log information inside onPostExecute: Does not appear
Remove the entire logic inside doInBackground so it's like this return "hello" : onPost still does not execute
You did not put #Override above onPostExecute. Also asynctask object must to be created inside UI thread.
EDIT: Your edittextis not updated, becauseit is consumedimidiatly after post execute is finished.
1) write EditText addrField; as class variable of activity class.
2) find reference to it in onCreate().
3) on your original onpostexecute should remain only addrField.setText(address);
there is my class, where textfields are updated from onPostexecute without any problems
public class AddToCheckActivity extends Activity {
// All static variables
private ProgressDialog pd = null;
// XML node keys
TextView active;
String addId = "";
JSONObject json = null;
ListView list;
String not_id, not_section, not_street, not_sqTotal, not_sqLiving,
not_sqKitchen, not_flat, not_floor, not_floors, not_text,
user_phone1, user_phone2, user_contact, not_region, not_district,
not_settle, not_price, not_photo, not_date, not_date_till, not_up,
not_premium, not_status, region_title, district_title,
settle_title, section_title, not_priceFor;
LinearLayout lin;
ImageView photo1;
ImageView photo2;
ImageView photo3;
Activity app;
ArrayList<String> photo_ids = new ArrayList<String>();
TextView address;
TextView date;
TextView date_till;
TextView description;
TextView district;
TextView flat;
TextView floor;
TextView floors;
TextView id;
TextView phone1;
TextView phone2;
TextView premium;
TextView region;
TextView section;
TextView settle;
TextView sqKitchen;
TextView sqLiving;
TextView sqTotal;
TextView uped;
TextView price;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aadd_addtocheck);
app = this;
lin = (LinearLayout) findViewById(R.id.lin);
address = (TextView) findViewById(R.id.tv_atc_address);
date = (TextView) findViewById(R.id.tv_atc_date);
date_till = (TextView) findViewById(R.id.tv_atc_date_till);
description = (TextView) findViewById(R.id.tv_atc_description);
district = (TextView) findViewById(R.id.tv_atc_dstrict);
flat = (TextView) findViewById(R.id.tv_atc_flat);
floor = (TextView) findViewById(R.id.tv_atc_floor);
floors = (TextView) findViewById(R.id.tv_atc_floors);
id = (TextView) findViewById(R.id.tv_atc_id);
phone1 = (TextView) findViewById(R.id.tv_atc_phone1);
phone2 = (TextView) findViewById(R.id.tv_atc_phone2);
premium = (TextView) findViewById(R.id.tv_atc_premium);
region = (TextView) findViewById(R.id.tv_atc_region);
section = (TextView) findViewById(R.id.tv_atc_section);
settle = (TextView) findViewById(R.id.tv_atc_settle);
sqKitchen = (TextView) findViewById(R.id.tv_atc_sqKitchen);
sqLiving = (TextView) findViewById(R.id.tv_atc_sqLiving);
sqTotal = (TextView) findViewById(R.id.tv_atc_sqTotal);
uped = (TextView) findViewById(R.id.tv_atc_uped);
price = (TextView) findViewById(R.id.tv_atc_price);
Bundle ex = getIntent().getExtras();
Log.d("Gues: ", "1");
Button back_button = (Button) findViewById(R.id.back_btn);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
pd = new ProgressDialog(app);
pd.setOwnerActivity(app);
pd.setTitle("Идет загрузка...");
pd.setCancelable(true);
if (ex != null) {
addId = ex.getString("add_id");
Log.d("Gues: ", "2");
not_id = not_priceFor = not_section = not_street = not_sqTotal = not_sqLiving = not_sqKitchen = not_flat = not_floor = not_floors = not_text = user_phone1 = user_phone2 = user_contact = not_region = not_district = not_settle = not_price = not_photo = not_date = not_date_till = not_up = not_premium = not_status = region_title = district_title = settle_title = section_title = "";
Log.d("Gues: ", "3");
GetAdd addvert = new GetAdd();
addvert.execute();
}
}
public void onClickBtnAtcDelete(View v) {
Thread t = new Thread(new Runnable() {
public void run() {
UserFunctions u = new UserFunctions();
u.deleteAdd(not_id);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
startActivity(i);
finish();
}
public void btnAtcEdit(View v) {
Intent i = new Intent(getApplicationContext(), AddSaveActivity.class);
final BitmapDrawable bitmapDrawable1 = (BitmapDrawable) photo1
.getDrawable();
final Bitmap yourBitmap1 = bitmapDrawable1.getBitmap();
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
yourBitmap1.compress(Bitmap.CompressFormat.PNG, 90, stream1);
byte[] imm1 = stream1.toByteArray();
final BitmapDrawable bitmapDrawable2 = (BitmapDrawable) photo2
.getDrawable();
final Bitmap yourBitmap2 = bitmapDrawable2.getBitmap();
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
yourBitmap2.compress(Bitmap.CompressFormat.PNG, 90, stream2);
byte[] imm2 = stream2.toByteArray();
final BitmapDrawable bitmapDrawable3 = (BitmapDrawable) photo3
.getDrawable();
final Bitmap yourBitmap3 = bitmapDrawable3.getBitmap();
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
yourBitmap3.compress(Bitmap.CompressFormat.PNG, 90, stream3);
byte[] imm3 = stream3.toByteArray();
i.putExtra("photo1", imm1);
i.putExtra("photo2", imm2);
i.putExtra("photo3", imm3);
i.putStringArrayListExtra("photo_ids", photo_ids);
i.putExtra("not_id", not_id);
i.putExtra("not_section", not_section);
i.putExtra("not_street", not_street);
i.putExtra("not_sqTotal", not_sqTotal);
i.putExtra("not_sqLiving", not_sqLiving);
i.putExtra("not_sqKitchen", not_sqKitchen);
i.putExtra("not_flat", not_flat);
i.putExtra("not_floor", not_floor);
i.putExtra("not_floors", not_floors);
i.putExtra("not_text", not_text);
i.putExtra("not_phone1", user_phone1);
i.putExtra("not_phone2", user_phone2);
i.putExtra("not_region", not_region);
i.putExtra("not_district", not_district);
i.putExtra("not_settle", not_settle);
i.putExtra("not_price", not_price);
i.putExtra("not_date", not_date);
i.putExtra("not_date_till", not_date_till);
i.putExtra("region_title", region_title);
i.putExtra("district_title", district_title);
i.putExtra("section_title", section_title);
i.putExtra("settle_title", settle_title);
i.putExtra("not_priceFor", not_priceFor);
startActivity(i);
}
public void onClickAtcGoToChooser(View v) {
Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
startActivity(i);
finish();
}
class GetAdd extends AsyncTask<Integer, Void, JSONObject> {
// private ProgressDialog pd = null;
private int op = 0;
#Override
protected void onPreExecute() {
// pd = new ProgressDialog(app);
// pd.setOwnerActivity(app);
// pd.setTitle("Идет загрузка...");
// pd.setCancelable(true);
pd.show();
}
#Override
protected JSONObject doInBackground(Integer... params) {
// TODO Auto-generated method stub
UserFunctions u = new UserFunctions();
// json = u.getNewAdd(addId);
return u.getNewAdd(addId);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
active = (TextView) findViewById(R.id.tv_atc_active);
photo1 = (ImageView) findViewById(R.id.imageP1);
photo2 = (ImageView) findViewById(R.id.imageP2);
photo3 = (ImageView) findViewById(R.id.imageP3);
ImageLoader imi = new ImageLoader(app.getApplicationContext());
if (result != null && result.has("not_id")) {
try {
Log.d("Gues: ",
"5_1 to status " + result.getString("not_status"));
// active.setText(json.getString("not_status")+"");
not_status = ("" + result.getString("not_status"));
not_region = ("" + result.getString("not_region"));
not_district = ("" + result.getString("not_district"));
not_settle = ("" + result.getString("not_settle"));
not_section = ("" + result.getString("not_section"));
not_street = (result.getString("not_street"));
not_date = (result.getString("not_date"));
not_price = (result.getString("not_price"));
not_date_till = (result.getString("not_date_till"));
not_text = (result.getString("not_text"));
district_title = (result.getString("district_title"));
not_flat = (result.getString("not_flat"));
not_floor = (result.getString("not_floor"));
not_floors = (result.getString("not_floors"));
not_id = (result.getString("not_id"));
user_phone1 = (result.getString("user_phone1"));
user_phone2 = (result.getString("user_phone2"));
not_premium = (result.getString("not_premium"));
region_title = (result.getString("region_title"));
section_title = (result.getString("section_title"));
settle_title = (result.getString("settle_title"));
not_sqKitchen = (result.getString("not_sqKitchen"));
not_sqTotal = (result.getString("not_sqTotal"));
not_sqLiving = (result.getString("not_sqLiving"));
not_up = (result.getString("not_up"));
LinearLayout l = (LinearLayout) findViewById(R.id.appDetail);
if (Integer.parseInt(not_section) == 1981
|| Integer.parseInt(not_section) == 1982) {
l.setVisibility(View.GONE);
}
not_priceFor = (result.getString("not_priceFor"));
String link1, link2, link3;
link1 = link2 = link3 = "";
JSONArray ar = result.getJSONArray("not_photos");
JSONArray pp = result.getJSONArray("photo_ids");
Log.d("ATC photo_ids", "-" + pp.length());
Log.d("ATC result", result.toString());
Log.d("ATC result pp", pp.toString());
Log.d("ATC result ppelement", pp.getString(0).toString());
for (int i = 0; i < pp.length(); i++) {
Log.d("ATC photo_ids pos", "-" + i);
Log.d("ATC result ppelement iter", pp.getString(i)
.toString());
photo_ids.add(pp.getString(i).toString());
}
// String[] ph = new String[3];
// for (int i =0; i< 3;i++){
// ph[i]=ar.getJSONObject(i).toString();
// }
imi.DisplayImage(ar.getString(0).toString(), photo1);
imi.DisplayImage(ar.getString(1).toString(), photo2);
imi.DisplayImage(ar.getString(2).toString(), photo3);
Log.d("Gues: ", "5_5");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Integer.parseInt(not_status) == 0) {
active.setText("Неактивно");
} else {
active.setText("Активно");
}
address.setText("Улица: " + not_street);
date.setText("Создано: " + not_date);
date_till.setText("Действительно до: " + not_date_till);
description.setText("Подробности объявления: " + "\n"
+ not_text);
district.setText("Город/поселок: " + district_title);
if (Integer.parseInt(not_section) == 1981
|| Integer.parseInt(not_section) == 1982) {
flat.setText("Машиномест: " + not_flat);
} else
flat.setText("Количество комнат: " + not_flat);
floor.setText("Этаж: " + not_floor);
floors.setText("Этажность: " + not_floors);
id.setText("ID: " + not_id + " ");
phone1.setText("Телефон: " + user_phone1);
phone2.setText("Телефон: " + user_phone2);
if (Integer.parseInt(not_premium) == 0) {
premium.setText("Обычное");
} else {
premium.setText(" Примиумное");
}
region.setText("Регион: " + region_title);
section.setText("В рубрике: " + section_title);
settle.setText("Район: " + settle_title);
sqKitchen.setText("Площадь кухни: " + not_sqKitchen);
sqTotal.setText("Общая площадь: " + not_sqTotal);
sqLiving.setText("Жилая площадь: " + not_sqLiving);
if (Integer.parseInt(not_up) == 0) {
uped.setText("");
} else {
uped.setText(" Поднятое ");
}
String priceT = "";
if (Integer.parseInt(not_priceFor) == 1)
priceT = "за все";
else if (Integer.parseInt(not_priceFor) == 2)
priceT = "за кв.м";
else if (Integer.parseInt(not_priceFor) == 3)
priceT = "за месяц";
else if (Integer.parseInt(not_priceFor) == 4)
priceT = "в сутки";
else if (Integer.parseInt(not_priceFor) == 5)
priceT = "в час";
else if (Integer.parseInt(not_priceFor) == 6)
priceT = "за кв.м./месяц";
else if (Integer.parseInt(not_priceFor) == 7)
priceT = "за сотку";
price.setText("Цена: " + not_price + " грн. " + priceT);
lin.setVisibility(View.VISIBLE);
} else {
error();
}
}
}
}
PS: t oavoid problems in future, don't put UI operations in any part of try{}