How to display image based on weather from drawable - android

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.

Related

my table is full in class and empty in other

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.

Why the Views are not updated with JSON parsed information

I'm having Problem in updating JSON parsed informations in my Views. Nothing is problem with getting JSON text from internet it works fine. I hope parsing process also looks good. Im having problem with Displaying contents in the Views.
package rev.app.revlearningdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class JsonFromInternet extends Activity {
String jsonText, name, weather_main, description, lon, lat, temp, pressure,
humidity, temp_min, temp_max, speed, deg;
long dt, sunrise, sunset;
TextView area, info, main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
area = (TextView) findViewById(R.id.weatherAreaName);
info = (TextView) findViewById(R.id.weatherInfo);
main = (TextView) findViewById(R.id.weatherMain);
Thread net = new Thread() {
public void run() {
URL url;
BufferedReader buff = null;
StringBuilder build = new StringBuilder();
try {
url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
buff = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
for (String l; (l = buff.readLine()) != null;)
build.append(l.trim());
} catch (IOException e1) {
Log.e("REV DEMO", "ERROR");
} finally {
if (buff != null)
try {
buff.close();
} catch (IOException e) {
Log.e("REV DEMO", "ERROR");
}
jsonText = build.toString();
interrupt();
}
};
};
net.start();
if (net.getState()==Thread.State.TERMINATED) {
parseJsonText(jsonText);
area.setText(name);
info.setText(description + "\n" + "Longitude, Lattitude " + lon
+ ", " + lat + "\nTemperature " + temp + "\n(Min:"
+ temp_min + ", Max:" + temp_max + ")\nPressure "
+ pressure + "\nHumidity " + humidity + "\nWind Speed "
+ speed + ", direction " + deg);
main.setText(weather_main);
}
}
private void parseJsonText(String jsonFromInternet) {
JSONObject root, coord, main, wind, sys, weather;
try {
root = new JSONObject(jsonFromInternet);
coord = root.getJSONObject("coord");
lon = coord.optString("lon");
lat = coord.optString("lat");
main = root.getJSONObject("main");
temp = main.optString("temp");
pressure = main.optString("pressure");
humidity = main.optString("humidity");
temp_min = main.optString("temp_min");
temp_max = main.optString("temp_max");
wind = root.getJSONObject("wind");
speed = wind.optString("speed");
deg = wind.optString("deg");
sys = root.getJSONObject("sys");
sunrise = sys.optLong("sunrise");
sunset = sys.optLong("sunset");
dt = root.optLong("dt");
name = root.optString("name");
weather = root.optJSONArray("weather").getJSONObject(0);
weather_main = weather.optString("main");
description = weather.optString("description");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You start asynchronous Thread to download the JSON and it means that your views are getting updated immediately (when your jsonText is not initialized yet).
Move updating your views into the end of run() method and update your views when you finished parsing data, not earlier. Warning: to call setText from thread you will have to use runOnUiThread method.
Thread net = new Thread() {
public void run() {
URL url;
BufferedReader buff = null;
StringBuilder build = new StringBuilder();
try {
url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
buff = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
for (String l; (l = buff.readLine()) != null;)
build.append(l.trim());
// parse and update views now:
jsonText = build.toString();
parseJsonText(jsonText);
runOnUiThread(new Runnable() {
#Override
public void run() {
area.setText(name);
info.setText(description + "\n" + "Longitude, Lattitude " + lon
+ ", " + lat + "\nTemperature " + temp + "\n(Min:"
+ temp_min + ", Max:" + temp_max + ")\nPressure "
+ pressure + "\nHumidity " + humidity + "\nWind Speed "
+ speed + ", direction " + deg);
main.setText(weather_main);
}
});
} catch (IOException e1) {
Log.e("REV DEMO", "ERROR");
} finally {
if (buff != null)
try {
buff.close();
} catch (IOException e) {
Log.e("REV DEMO", "ERROR");
}
interrupt();
}
};
};

How to display image from drawable?

i would like to display image from drawable.
However, I think that my if else having problem
because the statement for displaying image is correct..
and ya,
I would like to display the image based on the weather text.
Such as
<yweather:condition text="Light Rain" code="11" temp="26" date="Thu, 18 Jul 2013 12:00 pm SGT" />
so when I code it, it will display "logo.png" for the text "Light Rain"
Here are 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);
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;
}
}
switch(Integer.valueOf(conditionNode.getTextContent())){
case 11:
image.setImageResource(R.drawable.code11);
break;
default:
image.setImageResource(R.drawable.old);
}

Import yahoo contacts into android application

Hey anybody can tell me how can i import all yahoo contacts into my android application please , show me proper way dont give me yahoo api etc if u have source code kindly post it
thank you
just create a layout with webview , and use this code to get contacts.
you need oauth libraries,. and replace consumer key and scret with yours.
public class YahooContacts extends BaseActivity {
private final String TAG = "yahoo_auth";
private static final String CONSUMER_KEY = "you_consumer_key";
private static final String CONSUMER_SECRET = "your_consumer_secret";
private static final String CALLBACK_SCHEME = "http";
private static final String CALLBACK_HOST = "www.blablablao.com";
private static final String CALLBACK_URL = CALLBACK_SCHEME + "://"
+ CALLBACK_HOST;
private String AUTH_TOKEN = null;
private String AUTH_TOKEN_SECRET = null;
private String AUTH_URL = null;
private String USER_TOKEN = null;
private String ACCESS_TOKEN = null;
private String ACCESS_TOKEN_SECRET = null;
private String mUSER_GUID = null;
private WebView mWebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yahoo_layout);
mWebview = (WebView) findViewById(R.id.webview);
new getContactsTask().execute();
}
class getContactsTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
getAuthorizationToken();
getUserAutherization();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
private void getAuthorizationToken() {
String requestPath = "https://api.login.yahoo.com/oauth/v2/get_request_token?oauth_consumer_key="
+ CONSUMER_KEY
+ "&oauth_nonce="
+ System.currentTimeMillis()
+ "x"
+ "&oauth_signature_method=PLAINTEXT"
+ "&oauth_signature="
+ CONSUMER_SECRET
+ "%26"
+ "&oauth_timestamp="
+ System.currentTimeMillis()
+ "&oauth_version=1.0"
+ "&xoauth_lang_pref=en-us"
+ "&oauth_callback=" + CALLBACK_URL;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestPath);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
String[] data = responseBody.split("&");
AUTH_TOKEN = data[0].replace("oauth_token=", "");
AUTH_TOKEN_SECRET = data[1].replace("oauth_token_secret=", "");
AUTH_URL = data[3].replace("xoauth_request_auth_url=", "");
VIPLogger.info(TAG, "authToken" + AUTH_TOKEN);
VIPLogger.info(TAG, "authToken secret" + AUTH_TOKEN_SECRET);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getUserAutherization() {
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setWebViewClient(lWebviewClient);
mWebview.loadUrl("https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token="
+ AUTH_TOKEN);
}
private void getAccessToken() {
String requestPath = "https://api.login.yahoo.com/oauth/v2/get_token?oauth_consumer_key="
+ CONSUMER_KEY
+ "&oauth_nonce="
+ System.currentTimeMillis()
+ "x"
+ "&oauth_signature_method=PLAINTEXT"
+ "&oauth_signature="
+ CONSUMER_SECRET
+ "%26"
+ AUTH_TOKEN_SECRET
+ "&oauth_timestamp="
+ System.currentTimeMillis()
+ "&oauth_version=1.0"
+ "&oauth_token="
+ AUTH_TOKEN
+ "&oauth_verifier="
+ USER_TOKEN;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestPath);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
String[] data = responseBody.split("&");
ACCESS_TOKEN = data[0].replace("oauth_token=", "");
ACCESS_TOKEN_SECRET = data[1].replace("oauth_token_secret=", "");
mUSER_GUID = data[5].replace("xoauth_yahoo_guid=", "");
VIPLogger.info(TAG, "user guid: " + responseBody);
VIPLogger.info(TAG, "Access token: " + ACCESS_TOKEN);
getAllContacts();
} catch (Exception e) {
e.printStackTrace();
VIPLogger.error(TAG,
"error while fetching user guid and access token");
}
}
WebViewClient lWebviewClient = new WebViewClient() {
public void onPageStarted(WebView view, String url,
android.graphics.Bitmap favicon) {
if (url.contains("vipitservice")) {
mWebview.stopLoading();
int lastIndex = url.lastIndexOf("=") + 1;
VIPLogger.info(TAG, url.substring(lastIndex, url.length()));
USER_TOKEN = url.substring(lastIndex, url.length());
mWebview.setVisibility(View.GONE);
getAccessToken();
}
};
};
private void getAllContacts() {
HttpClient httpclient = new DefaultHttpClient();
String host_url = "http://social.yahooapis.com/v1/user/" + mUSER_GUID+ "/contacts";
String nonce = ""+System.currentTimeMillis();
String timeStamp = ""+(System.currentTimeMillis()/1000L);
try{
String params =
""+encode("oauth_consumer_key")+"=" + encode(CONSUMER_KEY)
+ "&"+encode("oauth_nonce")+"="+encode(nonce)
+ "&"+encode("oauth_signature_method")+"="+encode("HMAC-SHA1")
+ "&"+encode("oauth_timestamp")+"="+encode(timeStamp)
+ "&"+encode("oauth_token")+"="+ACCESS_TOKEN
+ "&"+encode("oauth_version")+"="+encode("1.0")
;
String baseString = encode("GET")+"&"+encode(host_url)+"&"+encode(params);
String signingKey = encode(CONSUMER_SECRET)+"&"+encode(ACCESS_TOKEN_SECRET);
VIPLogger.info(TAG, "base string: " + baseString);
String lSignature = computeHmac(baseString, signingKey);
VIPLogger.info(TAG, "signature: " + lSignature);
lSignature = encode(lSignature);
VIPLogger.info(TAG, "signature enacoded: " + lSignature);
String lRequestUrl = host_url
+ "?oauth_consumer_key="+CONSUMER_KEY
+ "&oauth_nonce="+nonce
+ "&oauth_signature_method=HMAC-SHA1"
+ "&oauth_timestamp="+timeStamp
+ "&oauth_token="+ACCESS_TOKEN
+ "&oauth_version=1.0"
+ "&oauth_signature="+lSignature
;
//VIPLogger.info(TAG, lRequestUrl.substring(1202));
HttpGet httpget = new HttpGet(lRequestUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
VIPLogger.info(TAG, "contacts response: " + responseBody);
}catch(Exception e){
e.printStackTrace();
VIPLogger.error(TAG, "error while fetching user contacts");
}
}
public String computeHmac(String baseString, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"),
"HMAC-SHA1");
mac.init(signingKey);
byte[] digest = mac.doFinal(baseString.getBytes());
String result = Base64.encodeToString(digest, Base64.DEFAULT);
return result;
} catch (Exception e) {
e.printStackTrace();
VIPLogger.error(TAG, "error while generating sha");
}
return null;
}
public String encodeURIComponent(final String value) {
if (value == null) {
return "";
}
try {
return URLEncoder.encode(value, "utf-8")
// OAuth encodes some characters differently:
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
// This could be done faster with more hand-crafted code.
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String encode(String input) {
StringBuilder resultStr = new StringBuilder();
for (char ch : input.toCharArray()) {
if (isUnsafe(ch)) {
resultStr.append('%');
resultStr.append(toHex(ch / 16));
resultStr.append(toHex(ch % 16));
} else {
resultStr.append(ch);
}
}
return resultStr.toString().trim();
}
private char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private boolean isUnsafe(char ch) {
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?#<>#%".indexOf(ch) >= 0;
}
}

Android: Cannot show more than one image

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.

Categories

Resources