The string concatenation is not displayed - android

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.

Related

Issues sharing a string between activities

I'm new at Android Programming and I'm having issues while trying to pass a String from an activity and an other one.
I've already added the needed code in manifest file.
I would like to take "myName" from user input in MainActivity and pass it to activity_matching, but in this second file the variable is always empty.
I can't understand what I'm doing wrong, so I'm here.
package com.ium.example.packageName;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity{
String myName;
EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
edit = findViewById(R.id.nickName);
myName = edit.getText().toString();
Button loginButton = findViewById(R.id.button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, activity_matching.class);
i.putExtra("myName", myName);
startActivity(i);
}
});
}
}
The code above is related to "MainActivity", the code below to "activity_matching"
package com.ium.example.packageName;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.snackbar.Snackbar;
import java.util.Random;
public class activity_matching extends AppCompatActivity {
float x1,x2,y1,y2;
int s;
String[] names = new String[17];
public String myName;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_matching);
}
public boolean onTouchEvent(MotionEvent touchEvent){
switch(touchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
y1 = touchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
y2 = touchEvent.getY();
Intent i = new Intent(activity_matching.this, SwipeLeft.class);
i.putExtra("num", s);
i.putExtra("arr", names);
startActivity(i);
break;
}
return false;
}
public void onBtnClick(View v) {
TextView txtHello = findViewById(R.id.txtMessage);
Intent b = getIntent();
myName = b.getStringExtra("myName");
String swipeLeft = "Swipe (a destra o sinistra) per l'argomento di discussione";
Snackbar doSwipe = Snackbar.make(v, swipeLeft, 6000);
Random rand = new Random(System.currentTimeMillis());
names = new String[]{"Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8",
"Name9", "Name10", "Name11", "Name12", "Name13", "Name14", "Name15",
"Name16", "Name17"};
re:
{
s = rand.nextInt(names.length);
if (myName.equals(names[s]))
break re;
txtHello.setText(myName + " vai a parlare con " + names[s] + "!");
doSwipe.show();
}
}
}
Thanks to everyone who will answer :3
Have a nice day ^-^
It may help to try to get your intent's extra data inside of the onCreate method. I'm not sure if this will help but I was having trouble replicating your problem on my end.
in MainActivity, you assign myName before you click loginButton. Your EditText was still empty at that time. move:
myName = edit.getText().toString();
to onClick above this line
i.putExtra("myName", myName);

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.

Passing strings to AsyncTask.execute in 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.

I am unable to retrieve the second value in Shared Preference

In my example, i am entering mobile no., message content in one activity. Before leaving that activity i am saving that info in "Shared Preference". In other activity i am trying to get those mob no,message,i am able to get no but unable to getting that message(second value).please help me to solve the issue.
DefaultDetails.java
package com.example.nirbhaya;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
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;
import android.widget.Toast;
public class DefaultDetails extends Activity implements OnClickListener{
Button save,reset;
EditText dMob,dMsg,dEmail;
String defMobNo,defMsg,defEmail;
SharedPreferences DefaultData;
private static final String TAG = "DD-Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.defaultdetails);
initializing();
}
private void initializing() {
// TODO Auto-generated method stub
save = (Button)findViewById(R.id.bsave1);
reset = (Button)findViewById(R.id.bReset);
dMob = (EditText)findViewById(R.id.etDefMobNo);
dMsg = (EditText)findViewById(R.id.etDefMsg);
dEmail = (EditText)findViewById(R.id.etDefEmail);
save.setOnClickListener(this);
reset.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.bsave1:
defMobNo = dMob.getText().toString();
defMsg = dMsg.getText().toString();
defEmail = dEmail.getText().toString();
Log.i(TAG,"DONE");
DefaultData = getSharedPreferences("defMobileNo",0);
SharedPreferences.Editor store = DefaultData.edit();
store.putString("defMobileNo", defMobNo);
store.putString("defMessgae", defMsg);
store.putString("defEMail", defEmail);
store.commit();
Intent openStartingPoint = new Intent (getApplicationContext(), CurrentDetails.class);
startActivity(openStartingPoint);
break;
case R.id.bReset:
((EditText) findViewById(R.id.etDefMobNo)).setText("");
((EditText) findViewById(R.id.etDefEmail)).setText("");
((EditText) findViewById(R.id.etDefMsg)).setText("");
break;
}
}
}
DefSMS.java
package com.example.nirbhaya;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class DefSms extends Activity{
Button buttonSend;
String defNo,defMsg;
SharedPreferences DefaultData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.defsms);
DefaultData = getSharedPreferences("defMobileNo",0);
final String defNo = DefaultData.getString("defMobileNo","Couldn't load data");
DefaultData = getSharedPreferences("defMessgae",0);
final String defMsg = DefaultData.getString("defMessgae","Couldn't load data");
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(defNo, null, defMsg, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
Here def no getting message as Couldn't load data
please help me
Replace with this:
DefaultData = getSharedPreferences("defMobileNo",0);
final String defNo = DefaultData.getString("defMobileNo","Couldn't load data");
final String defMsg = DefaultData.getString("defMessgae","Couldn't load data");
This is how basically sharedpreference work
To Store the values
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","myNameisnothing");
editor.commit();
To get the values
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String name = prfs.getString("Name", "");
This way it'd return the value of the name as myNameisnothing.
PS.Correct me if im wrong.
You are wrongly using
DefaultData = getSharedPreferences("defMessgae",0); in DefSMS.java
Please remove this and it will work fine.
You were trying to get shared preference named defMessgae which doesnot even exist. So when you try to access it, android will create a new preference with default value. That is why you were getting "Couldn't load data"

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