Passing strings to AsyncTask.execute in android? - android

Im trying to make a weather app in android where i get input from user and then tell them the current weather. main activity looks like this
package com.example.dellinspiron.speechrecognition;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.graphics.Typeface;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;
Typeface weatherFont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button);
assert b != null;
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText c=(EditText)findViewById(R.id.city);
EditText d=(EditText)findViewById(R.id.country);
final String city=c.getText().toString();
final String country=d.getText().toString();
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");
cityField = (TextView)findViewById(R.id.city_field);
updatedField = (TextView)findViewById(R.id.updated_field);
detailsField = (TextView)findViewById(R.id.details_field);
currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field);
humidity_field = (TextView)findViewById(R.id.humidity_field);
pressure_field = (TextView)findViewById(R.id.pressure_field);
weatherIcon = (TextView)findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: "+weather_humidity);
pressure_field.setText("Pressure: "+weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
asyncTask.execute(city, country); // having problems here
}
});
}
when i try to explicitly pass the city name and country eg asyncTask.execute("rawalpindi", "Pakistan") it works, but then if i try to pass a string obtained from the text box it doesnt.
i have tried to get output of the string and it gives the correct output but it just isnt being passed to the execute function properly. please help.

Try to trim the string using trim() method when you obtain the text from EditText as extra spaces may cause the error in the result.

Related

Passing data always comes back 0

I have fixed the problem that I originally create this question for, but now I have a new problem. The activity gets created and it goes to my other screen when I select the button, but now the value that is suppose to get passed to the second activity always comes back as 0.
I am assuming this is the line that is causing it? How, would I fix that?
int goal = intent.getIntExtra("calorieGoal", 0);
My Main Activity.java
package net.androidbootcamp.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
String selection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//gets data from the user input
final EditText weight = (EditText)findViewById(R.id.bodyWeight);
final EditText age = (EditText)findViewById(R.id.yearsOld);
final EditText height = (EditText)findViewById(R.id.inchHeight);
//gets the spinner selection
final Spinner activityLevel = (Spinner)findViewById(R.id.activityLevel);
//initate the button, and set code for when the button is clicked
Button lose = (Button)findViewById(R.id.loseButton);
lose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userWeight = weight.getText().toString();
String userheight = height.getText().toString();
String userAge = age.getText().toString();
int uWeight = Integer.parseInt(userWeight);
int uHeight = Integer.parseInt(userheight);
int uAge = Integer.parseInt(userAge);
double calorieGoal;
selection = activityLevel.getSelectedItem().toString();
if(selection == "sedentary"){
double bmr = 66.47 + (6.24 * uWeight) + (12.7 * uHeight) - (6.75 * uAge);
calorieGoal = bmr * 1.2;
Intent intent = new Intent(MainActivity.this, Gain_Activity.class);
intent.putExtra("calorieGoal", calorieGoal);
startActivity(intent);
}
}
});
}
}
second activity that I am trying to send the data to
package net.androidbootcamp.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Gain_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gain_);
Intent intent = getIntent();
int goal = intent.getIntExtra("calorieGoal", 0);
TextView texview = findViewById(R.id.calorieGoal);
texview.setText(goal);
}
}
calorieGoal is of type double, not int. You will not be able to get it via getIntExtra.
Try getDoubleExtra.

getText is not working in Android studio

package com.example.mediosa.mediosa;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.firebase.client.Firebase;
public class registerActivity extends AppCompatActivity {
private Button buttonSignIn, buttonRegister;
private EditText editTextUsername;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextDOB;
private EditText editTextName;
private RadioButton radioButtonMale, radioButtonFemale;
private Firebase rootRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
rootRef = new Firebase(FIREBASE_URL");
buttonSignIn = (Button)findViewById(R.id.buttonSignIn);
editTextDOB = (EditText)findViewById(R.id.editTextDOBReg);
editTextUsername = (EditText)findViewById(R.id.editTextUsernameReg);
editTextEmail = (EditText)findViewById(R.id.editTextEmailReg);
editTextPassword = (EditText)findViewById(R.id.editTextPasswordReg);
editTextName = (EditText)findViewById(R.id.editTextNameReg);
radioButtonFemale =(RadioButton)findViewById(R.id.radioButtonFemale);
radioButtonMale = (RadioButton)findViewById(R.id.radioButtonMale);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(registerActivity.this ,
LoginActivity.class));
}
});
final String Name = editTextName.getText().toString();
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(registerActivity.this, Name ,
Toast.LENGTH_SHORT).show();
}
});
}
}
I am new to Android and was working on a project.
In this code (Part of that project) in am unable to read data from user as name. The compiler shows no error And the code works correctly but when i try to show the data in the Name string using toast, it is completely blank.
I need this name and other field to store data in Firebase DB, but it was not working and i found out there was some problem in reading data.
Would be really great if anyone can help me, thanks.
The problem is that you are not updating the value of Name , meanwhile there is no need for a variable if you only want to display the text. Here is how you display the text.
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(registerActivity.this,
editTextName.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
Try putting getText() inside the OnClickListener:
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name = editTextName.getText().toString();
Toast.makeText(registerActivity.this, Name ,
Toast.LENGTH_SHORT).show();
}
});
This is because you call getText() inside onCreate(). see where it is placed. Thus when the Activity is being created, the text inside EditText is empty.

Get the calculation of random numbers to compare with an EditText

Recently I have been trying how to get the calculation of two random numbers that are shown in MainActivity to compare later with the text field and indicate if the number inserted is correct or no.
Here the code:
MainActivity.java
package com.example.miguel.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
Random random = new Random();
int randomNum = random.nextInt(101);
int randomNum2 = random.nextInt(101);
String messageRandomNum = String.valueOf(randomNum);
String messageRandomNum2 = String.valueOf(randomNum2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textViewRandomNum = (TextView) findViewById(R.id.random_num);
textViewRandomNum.setText(messageRandomNum);
messageRandomNum2 = String.valueOf(randomNum2+ "= ");
TextView textViewRandomNum2 = (TextView) findViewById(R.id.random_num2);
textViewRandomNum2.setText(messageRandomNum2);
}
public int getCalculation(){
//Here is where I had tried to get the calculation of the same numbers that are shown in the screen
int calculation = randomNum + randomNum2;
return calculation;
}
public void sendMessage (View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package com.example.miguel.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
MainActivity mainActivity = new MainActivity();
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int messageInt = Integer.parseInt(message);
TextView textView = new TextView(this);
textView.setTextSize(40);
//The comparison of editText and the calculation
if(messageInt == mainActivity.getCalculation()){
textView.setText("Correct!");
}else{
textView.setText("Incorrect!");
}
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
Always is shown that the inserted number (although it is well) shows "Incorrect!". I don't know why the calculation does a sum of random numbers, but not the random numbers than are shown in the screen.
If you don't understand something, sorry, I'm a Spanish speaker.
Regards! ;)
In MainActivity you can send calculated result
public void sendMessage (View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
int calcualtedResult=getCalculation();
intent.putInt("calcualtedResult", calcualtedResult);
startActivity(intent);
}
In DisplayMessageActivity
you can get the intent
int calculatedRes=intent.getInt("calculatedResult");
if(messageInt == calculatedRes){
textView.setText("Correct!");
}else{
textView.setText("Incorrect!");
}
wrong thing in your code is that you create an object from MainActivity in your DisplayMessageActivity. this object differ from activity that call DisplayMessageActivity and hasn't your random numbers. you must send random numbers with intent to next Activity, like EXTRA_MESSAGE.

The string concatenation is not displayed

I have a problem with the concatenation of the strings that I will I enter.
This is the class:
package com.isma.multisitesearch.Siti;
import com.isma.multisitesearch.R;
import com.isma.multisitesearch.Webviews.GoogleWebView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Google extends Activity implements OnClickListener {
private String TAG_ACT = "Caricamento ricerca";
public EditText googletext;
private Button googlebutton;
private String googleurl = "https://www.google.it/search?q=";
public static String newgoogleurl;
public String space = " ";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.google);
googletext = (EditText) findViewById(R.id.googletext);
googlebutton = (Button) findViewById(R.id.googlebutton);
googlebutton.setOnClickListener(this);
newgoogleurl = googleurl + googletext.getText().toString();
newgoogleurl.replaceAll(space, "%20");
System.out.println(newgoogleurl);
}
#Override
public void onClick(View v) {
Log.v(TAG_ACT, "in corso");
Intent intent = new Intent(Google.this, GoogleWebView.class);
startActivity(intent);
}
}
And this is the WebView to which I want to get the concatenation:
package com.isma.multisitesearch.Webviews;
import com.isma.multisitesearch.R;
import com.isma.multisitesearch.Siti.Google;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class GoogleWebView extends Activity {
private WebView googlewebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.googlewebview);
googlewebview = (WebView) findViewById(R.id.googlewebview);
googlewebview.getSettings().setJavaScriptEnabled(true);
googlewebview.getSettings().setLoadsImagesAutomatically(true);
googlewebview.setWebViewClient(new WebViewClient());
googlewebview.loadUrl(Google.newgoogleurl);
}
}
The app works fine but when I go to write the search text in the EditText, the google but I get the main page where you can enter the search instead of the url with already entered the search text.
I hope you know to help me, after this I was able to run the app.
Try this:
#Override
public void onClick(View v) {
newgoogleurl = googleurl + googletext.getText().toString();
newgoogleurl = newgoogleurl.replaceAll(space, "%20");
Log.v(TAG_ACT, "in corso");
Intent intent = new Intent(Google.this, GoogleWebView.class);
startActivity(intent);
}
Note that
newgoogleurl.replaceAll(space, "%20");
has no effect, you need to code:
newgoogleurl = newgoogleurl.replaceAll(space, "%20");
Have a look here:
http://javarevisited.blogspot.it/2011/12/java-string-replace-example-tutorial.html
Try below code:
String url;
url = googleurl+googletext.getText().toString();
if( url.contains(" ")){
newgoogleurl=url.replaceAll(" ","%20");
}else{
newgoogleurl=url;
}
This is containing validation part also.
Strings are immutable. That means that you cannot modify an instance of String, and need to create a new one each time you want to modify it.
In your case, replaceAll does not modify the String you call it on, but rather returns a new String with your modification applied.
Which is why you need to affect the returned value to the reference of your String.
newgoogleurl = newgoogleurl.replaceAll(space, "%20");
Moreover, you should read the documentation for replaceAll, because I don't think it does what you want. You probably want to use replace.

HTMLcleaner in AsyncTask

I am trying to get HTML cleaner to parse the info from a website and then use Xpath to find the data I'm looking for. I have the htmlcleaner stuff in a separate AsyncTask class and the app seems to work on my phone. However, when I push the button nothing happens. Here is my main activity class and my AsyncTask Class.
package ru.habrahabr.stackparser;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.htmlcleaner.TagNode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class stackParser extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.parse);
button.setOnClickListener(myListener);
}
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
new parseSite().execute("http://xjaphx.wordpress.com/");
}
};
private class parseSite extends AsyncTask<String, Void, String> {
protected String doInBackground(String... arg) {
String output = new String();
try {
htmlHelper hh = new htmlHelper();
} finally {
}
return output;
}
protected void onPostExecute(String output) {
TextView view = (TextView) findViewById(R.id.tv1);
view.setText((CharSequence) output);
}
}
}
And here's my referenced class. I'd really appreciate it if someone could look at this and tell me what's up. I tried to follow a working example and put my own Url and Xpath in but it's not working.
package ru.habrahabr.stackparser;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
public class htmlHelper {
TagNode rootNode;
String stats;
static final String XPATH_STATS = "//div[#id='blog-stats']/ul/li";
public String htmlHelper(URL htmlPage) throws IOException, XPatherException {
HtmlCleaner cleaner = new HtmlCleaner();
rootNode = cleaner.clean(htmlPage);
// query XPath
Object[] statsNode = rootNode.evaluateXPath(XPATH_STATS);
// process data if found any node
if (statsNode.length > 0) {
TagNode resultNode = (TagNode) statsNode[0];
stats = resultNode.getText().toString();
}
return stats;
}
}
Change AsyncTask doInBackground method as :
#Override
protected String doInBackground(String... arg) {
String output "";
try {
htmlHelper hh = new htmlHelper();
output=hh.htmlHelper(arg[0]); //<< call htmlHelper method here
} finally {
}
return output;
}
because you are currently only creating an instance of htmlHelper class not calling htmlHelper method from htmlHelper class to get data from web url
Look , I will not care of the data is downloaded or not , but I will assume that the data is already downloaded and besides in the variable output , you just need to place this code inside onPostExecute
runOnUiThread(new Runnable() {
public void run() {
// update data into TextView.
TextView view = (TextView) findViewById(R.id.tv1);
view.setText((CharSequence) output);
}
});
because , sometimes the data is already downloaded but needed to be assigned into Textview or whatever view by using UIthread. Hope this works for you

Categories

Resources