I have some code that uses JSoup and connects to a website successfully in JAVA.
I am trying to duplicate the exact same thing (as a learning experience) on the Android.
I am using Eclipse.
Within my activity_main.xml I have 3 buttons and a text field.
I do not have any errors within my JAVA code and have confirmed it still works within JAVA (running in Netbeans)
I have my JSoup jar within the libs folder ~ that was an issue that took a little while to find.
I have placed some editText.setText(“Here”); to see where the code gets.
I have a message immediately below my doc = JSoup.connect(“http://www.Google.com”).get();
I never get that message.
Likewise I have the same message within my catch routine – I am always getting into the catch routine, meaning I have a problem.
I have tried this two ways – with the android emulator and with my phone attached through the USB cable. I get the same result – the “app” runs fine but displays the message found within the catch{}.
I am at a loss since the exact code works fine within Netbeans / regular JAVA.
Here is my code:
package com.example.duckriver;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.helper.Validate;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int counter;
Button Button1;
Button SummaryStats;
TextView display;
TextView editText;
String dataread = null;
String high = "High:";
String low = "Low:";
String filename = null;
int index = 0;
int startindex = 0;
int lastindex = 0;
int length = 0;
char[] CharArray = new char[1000];
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
counter = 0;
Button1 = (Button) findViewById(R.id.button1);
SummaryStats = (Button) findViewById(R.id.buttonSummaryStats);
display = (TextView) findViewById(R.id.tvMainDisplay);
editText = (TextView) findViewById(R.id.editText);
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
//counter++;
Document doc;
try{
doc=Jsoup.connect("http://www.Google.com").get();
editText.setText("Here");
//get Title
//String title = doc.title();
//System.out.println("Title: "+title);
//dataread = doc.body().text(); // "An example link"
Element link = null;
}//end try
catch(Exception ex){
ex.printStackTrace();
editText.setText("Error");
//((TextView)findViewById(R.id.tv)).setText("Error");
}// end catch
}
});
SummaryStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter = counter*counter;
}
});
return true;
}
}
I am at a loss. Help?
Thanks.
You need download document with Asyncronous task or Android will throw exception. Try this:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
counter = 0;
Button1 = (Button) findViewById(R.id.button1);
SummaryStats = (Button) findViewById(R.id.buttonSummaryStats);
display = (TextView) findViewById(R.id.tvMainDisplay);
editText = (TextView) findViewById(R.id.editText);
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
downloadDocTask task = new downloadDocTask();
task.execute("www.google.com");
}
});
SummaryStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter = counter*counter;
}
});
return true;
}
private class downloadDocTask extends AsyncTask<String, Void, Document>{
String urldisplay;
#Override
protected Document doInBackground(String... urls) {
urldisplay = urls[0];
Document doc = null;
try {
doc = Jsoup.connect(urldisplay).timeout(10*1000).get();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
#Override
protected void onPostExecute(Document result) {
if(result != null){
Log.i(TAG, "downloadDocTask.onPostExcecute Document Download complete");
buildHtml(result);
}
else{
Log.i(TAG, "downloadDocTask.onPostExcecute Document == null");
}
}
}
public void buildHtml(Document doc){
// Parse document here
String title = doc.title();
}
Related
I'm calling a
(getData()
that should run HttpURLConnection and return a string (later to be casted as Long), the string should be the one line from this URL:
https://blockchain.info/tobtc?currency=USD&value=1
Trying to see if it is returning anything , I'm displaying the returned string in the layout.xml file and showing a toast. But both both show as blank
Please do not pay attention to the fact that I'm doing this on the main thread, I'm just trying to make it work first.
What I'm I doing wrong? why it's not returning the string value.
thanks
package app.com.cryptosudan.android.cryptosudan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton sdg = (ImageButton) findViewById(R.id.imagesdg);
ImageButton btc = (ImageButton) findViewById(R.id.imagebtc);
final TextView display = (TextView) findViewById(R.id.display);
String price;
price = (getData());
display.setText(price);
Toast.makeText(this, price, Toast.LENGTH_LONG).show();
sdg.setOnClickListener(sdgpage);
btc.setOnClickListener(btcpage);
}
//to create an instance of button OnClickListener
View.OnClickListener sdgpage = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CalculateSdg.class));
}
};
//to create an instance of button OnClickListener
View.OnClickListener btcpage = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CalculateBtc.class));
}
};
public static String getData () {
BufferedReader reader = null;
try {
URL url = new URL("https://blockchain.info/tobtc?currency=USD&value=1");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) !=null) {
sb.append (line + "/n");
} return sb.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#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_main, 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);
}
}
For http request on main thread change you onCreate method with StrictMode.ThreadPolicy.Builder().permitAll()
I Don't recommend Http request in main thread !!!!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton sdg = (ImageButton) findViewById(R.id.imagesdg);
ImageButton btc = (ImageButton) findViewById(R.id.imagebtc);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView display = (TextView) findViewById(R.id.display);
String price;
price = (getData());
display.setText(price);
Toast.makeText(this, price, Toast.LENGTH_LONG).show();
sdg.setOnClickListener(sdgpage);
btc.setOnClickListener(btcpage);
}
I have written this code for searching a text file for a string. The problem is, it says that the string is not found even if it is present. Process is to receive the text from the EditText and then start the searching process. But it shows that string is found every time.
package com.example.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button;
final EditText obedittext;
button =(Button)findViewById(R.id.button1);
obedittext =(EditText)findViewById(R.id.editText1);
button.setOnClickListener(
new View.OnClickListener()
{
boolean textfound;
public void onClick(View view)
{
textfound = searchtext(obedittext.getText().toString());
if(textfound)
maketoast(obedittext.getText().toString());
else
maketoast("Unsuccessfull");
}
});
}
protected boolean searchtext(String string) {
// TODO Auto-generated method stub
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new InputStreamReader(getAssets().open("mneumo.txt")));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.equals(string)) {
return true;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
finally{
}
return false;
}
private void maketoast(String string) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, string , Toast.LENGTH_SHORT);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So when i tried to give the string inside the code itself instead of getting it from the edittext,it works fine. Like this,
string = "SPINAL ANESTHESIA AGENTS";
The sample text file is,
SPINAL ANESTHESIA AGENTS
XYLOCAINE: WHERE NOT TO USE WITH EPINEPHRINE
GENERAL ANAESTHESIA: EQUIPMENT CHECK PRIOR TO INDUCING
So how can i rectify this problem? Can anyone say why i am getting this problem?
Should i any other method to compare the strings?
The text file is correctly placed in the assets folder. And i accessed it using the assetmanager. And i am a total newbie to android development.
May be your editText contain some white space already, To get text from your editText try this:
obedittext.getText().toString().trim();
and inside your searchtext() method, replace your if condition with:
if(sCurrentLine.equalsIgnoreCase(string))
This method works fine.
public void onClick(View view) {
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
EditText login = (EditText) findViewById(R.id.loginfld);
EditText passw = (EditText) findViewById(R.id.passfld);
String logincmd = "CheckLogin*" + login.getText() + "*" + passw.getText() + "*";
ss.senddata(logincmd, 1);
}
In this method java.lang.NullPointerException appears (on btn.setVisibility(View.VISIBLE);
public void geturdata(String answer) {
if (answer != null)
{
System.out.println("true");
btn.setVisibility(View.VISIBLE);
}
else
{
System.out.println("false");
}
}
Please tell me how can I call button in this method? Also I can't use StartActivity(intent) in this method.(same error). Both metods placed in one activity.
Here is full code
This is activity
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class Login extends Activity {
SocketServer ss = new SocketServer();
Button btn;
ProgressBar progr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
try {
ss.setserver();
} catch (Exception ex) {
System.out.println("------- " + ex);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add("menu1");
getMenuInflater().inflate(R.menu.login, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view) {
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
EditText login = (EditText) findViewById(R.id.loginfld);
EditText passw = (EditText) findViewById(R.id.passfld);
String logincmd = "CheckLogin*" + login.getText() + "*" + passw.getText() + "*";
ss.senddata(logincmd, 1);
}
public void geturdata(String answer) {
if (answer != null)
{
System.out.println("true");
btn.setVisibility(View.VISIBLE);
}
else
{
System.out.println("false");
}
}
}
And this is class that call >geturdata
import android.os.Looper;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketServer {
private Socket socket;
private static final int SERVERPORT = 11000;
private static String SERVER_IP = "192.168.2.222";
String answer;
private static String cmdtext;
private static int caller;
class ClientThread implements Runnable
{
public void run() {
if (cmdtext.equals("setserver"))
{
try
{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
}
catch (Exception ex)
{System.out.println(ex);}
}
else {
try {
String str = cmdtext;
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
byte[] data = new byte[256];
InputStream inp = socket.getInputStream();
inp.read(data);
answer = new String(data, "UTF-8");
Looper.prepare();
handledata(answer);
Looper.loop();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
////////////////////////////////////////
public void setserver ()
{
new Thread(new ClientThread()).start();
cmdtext = "setserver";
}
private void handledata(String answer)
{
switch (caller) {
case 1:
{
Login lgn = new Login();
lgn.geturdata(answer);
}
}
}
public void senddata(String cmd, int callerid)
{
this.cmdtext = cmd;
this.caller = callerid;
new Thread(new ClientThread()).start();
}
}
btn is null when you call geturdata(). You should call btn = (Button) findViewById(R.id.trytogetin); directly after setContentView(R.layout.activity_main); in public void onCreate(Bundle b)
private Button btn;
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.trytogetin);
...
}
EDIT:
But, seeing your code now, thats not the problem. There are two problems here
Login lgn = new Login();
lgn.geturdata(answer);
You try to instantiate an Activity. You should start activities through intents, so that they are instanciated in the normal Activity lifecycle: through onCreate.
But there's more: You try to set the Button from another Thread than the one which created the Button (the UI-thread)
You can try to get a handle from the context in the thread, and call context.runOnUiThread(Runnable). That way you can update the UI from other Threads.
So the NPE is caused by the fact that you instantiate Login (which has to be done by Android), and call a method, but theres no ContentView inflated, so the Button is not found anyway, findViewById returns null
You are getting id of button inside click method. So to solve the problem , get your button id in oncreate() method. So you can access button anywhere. But declare button globaly
Declare this in OnCreate()
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
public void onClick(View view) {
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
}
String logincmd = "CheckLogin*" + login.getText().toString() + "*" + passw.getText().toString() + "*";
So reference to this method geturdata where you used object of Button btn returns null, since you used inside onClick button.
public void geturdata(String answer) {
I'm trying to start another activity in my main activity using this method:
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
Intent intent = new Intent(getApplicationContext(),ReadOut.class);
intent.putExtra("response", res);
startActivity(intent);
}
This starts the following class:
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ReadOut extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
boolean paused = false;
String leftToRead = null;
String res = null;
TextToSpeech tts;
protected void onPreExecute()
{
System.out.println("Pre-execute");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_out);
Intent intent = getIntent();
res = intent.getExtras().getString("response");
TextView textv = (TextView) findViewById(R.id.textView1);
textv.setText(res);
textv.setMovementMethod(new ScrollingMovementMethod());
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
textv.setHeight((int)(display.getHeight()*0.76));
System.out.println("START");
tts = new TextToSpeech(this, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
public String speakFull(String text){
System.out.println("Speaking: " + text);
System.out.println("Speaking");
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
if(!tts.isSpeaking() && !paused){
System.out.println("Speaking: " + i);
tts.speak(sentences[i], TextToSpeech.QUEUE_FLUSH, null);
}else if(paused){
System.out.println("Paused");
String paused = "";
int k = 0;
if(i != 0){
k = i-1;
}
leftToRead = null;
for(int j = k; j < sentences.length; j++){
leftToRead += sentences[j];
}
return leftToRead;
}else{
i--;
System.out.println("Sleeping");
System.out.println("Speaking : " + tts.isSpeaking());
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
if(i == sentences.length - 1){
return "Message 001: Complete";
}
}
return null;
}
#Override
public void onInit(int arg0) {
System.out.println("speakFull");
leftToRead = speakFull(res);
}
public void clickPause(View v){
if(paused){
paused = false;
Button b = (Button) findViewById(R.id.button1);
b.setText("Play");
}else{
paused = true;
Button b = (Button) findViewById(R.id.button1);
b.setText("Pause");
if(leftToRead == null){
leftToRead = speakFull(res);
}else{
leftToRead = speakFull(leftToRead);
}
}
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
After the ReadOut class is started one of a couple things can happen,
either the screen turns black, the text to speech begins reading, and the app is telling me it's not responding, OR it shows me the view for ReadOut, reads in text to speech, and then tells me it's not responding.
I'm really confused as to why this is happening, and any insight would be appreciated.
I don't know anything about using TTS but I can tell you that this line is probably causing a problem
Thread.sleep(1000);
It appears you are calling it on the UI Thread which isn't a good idea. You need to use a background Thread and update it with something like runOnUiThread() or AsyncTask or you could use a Handler.
I designed a custom keyboard using ImageButtons for Android (using Eclipse). I want to click on a button to write on the text, but every time I click a button, it resets the text, erasing what I previously wrote.
How can I get it to continue writing from the previous text?
This is a basic bit of my code, using two buttons and a text field.
package com.example.nonachan;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
char g;
char h;
int i = 0;
//char buf[] = new char[10];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText t =(EditText)findViewById(R.id.t1);
ImageButton n = (ImageButton)findViewById(R.id.b1);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
g = 'd';
// buf[i] = 'd';
t.setText( "" + g);
i++;
}
});
ImageButton a = (ImageButton)findViewById(R.id.b2);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// buf[i] = 'h';
h = 'h' ;
t.setText( "" +h);
i++;
}
});
Button l = (Button)findViewById(R.id.b3);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
t.setText( "" + g);
The above line in your code says to set t's text to "" + g which is equal to "d". It will never append the text since you don't tell it to.
Try adding the existing text in the text field:
t.setText(t.getText().toString() + g);
And you'll have to do the same with t.setText( "" +h); as well.