I am getting an email echoed from PHP script. And I am loading that into textview in an Android application. It's right now being showed as text. How can I display it as a hyperlink so that I can click it to go to email?
package com.example.login2;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class SAppointmentActivity extends Activity {
TextView news;
#Override
protected void onCreate(Bundle savedInstanceState1) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState1);
setContentView(R.layout.snews);
news = (TextView)findViewById(R.id.news);
news.setText("Hello");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
MyApp MyAppVar = new MyApp();
postParameters.add(new BasicNameValuePair("username", MyAppVar.getName()));
postParameters.add(new BasicNameValuePair("password", MyAppVar.getPasswd()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://192.168.1.8/appointment.php", postParameters);
String res=response.toString();
// res = res.trim();
//res= res.replaceAll("\\s+","");
news.setText(res);
}
catch (Exception e) {
news.setText("Error");
}
}
}
Linkify.addLinks(news, Linkify.EMAIL_ADDRESSES);
TextView email = (TextView)findViewById(R.id.TextView04);
email.setText("sadasd asmn#gmail.com");
email.setLinkTextColor(Color.WHITE);
Linkify.addLinks(email,Linkify.EMAIL_ADDRESSES);
This is the working code. Just try it.
Related
i Edited all my previous question . I solved that long time ago .
but now i am here and just getting all things done :
i have a login activity :
which makes a call to rest api with credentials .
i have created the login activity it works ok but i have to press the button two times in order to perform some action . i think there is a mistake in my code :
here is my login activity ... if anyone can help me in this i will accept it as answer and will close this link on my stickies....
login.java:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class login_act extends Activity {
private ProgressDialog pDialog;
List<NameValuePair> params=null;
static String response = null;
private String url = "http://hostname_ip/rest-api/xxxxx/?format=json";
static String u="";
static String p="";
String temp= "";
// User name
private EditText et_Username;
// Password
private EditText et_Password;
// Sign In
private Button bt_SignIn;
// Message
private TextView tv_Message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
// Initialization
et_Username = (EditText) findViewById(R.id.u_name);
et_Password = (EditText) findViewById(R.id.password);
bt_SignIn = (Button) findViewById(R.id.sign_in);
tv_Message = (TextView) findViewById(R.id.statusop);
bt_SignIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Stores User name
String username = String.valueOf(et_Username.getText());
u=username;
// Stores Password
String password = String.valueOf(et_Password.getText());
p=password;
new Getlogin().execute();
}
});
}
private class Getlogin extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(login_act.this);
pDialog.setMessage("Signing In...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
String credentials = u + ":" + p;
try {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
String base64EncodedCredentials = Base64.encodeBytes(credentials.getBytes());
httpGet.addHeader("Authorization", "Basic " + base64EncodedCredentials);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
temp = response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
try {
pDialog.dismiss();
if(temp.contains("count")){
tv_Message.setText("Logged In");
Intent go = new Intent(login_act.this,Scnd.class);
Bundle extras = new Bundle();
extras.putString("status", response);
extras.putString("user", u);
extras.putString("pass", p);
// 4. add bundle to intent
go.putExtras(extras);
startActivity(go);
finish();
}else
tv_Message.setText("Invalid username or password");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
i only want if user and pass are ok then intent to new activity . if the user pasword are wrong then display response with incorect user password
but the activity performs it by clicking twice a button . i want to make it single click.. any help ?? i would be thankful.
You need to have an installation of Newfies-Dialer in order to use the API, in other words the API url will be the one from your own server.
The documentation clearly say API URL => http://HOSTNAME_IP/rest-api/campaigns/
in my application i am fetching json data from online server. and after that i am trying to display the data by toast. but the application stop working. if i commented the toast section then the application runs smoothly. so i think there is a problem in toast section. so guys plz help me to find out the reason for the problem
package com.example.getdata;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity {
EditText password,username;
String pass,user;
//TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onConnect(View v) {
new Thread(){
public void run(){
HttpClient myClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://tusharinfotech.com/debasish/get_data.php");
try {
List<NameValuePair> myArgs = new ArrayList<NameValuePair>();
// myArgs.add(new BasicNameValuePair("username", user));
// myArgs.add(new BasicNameValuePair("password", pass));
post.setEntity(new UrlEncodedFormEntity(myArgs));
HttpResponse myResponse = myClient.execute(post);
BufferedReader br = new BufferedReader( new InputStreamReader(myResponse.getEntity().getContent()));
String line = "";
String data1 ="";
while ((line = br.readLine()) != null)
{
try {
JSONArray myarray = new JSONArray(line);
for(int i=0;i<myarray.length();i++){
JSONObject jsonObject = myarray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("FOOD_ID").toString());
String name = jsonObject.optString("FOOD_NAME").toString();
data1 += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n ";
}
//Log.d("mytag",data);
//this application stop working for this toast part.. if i commented it then the application run smoothly
Toast.makeText(getApplicationContext(),data1, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//EditText output1 = (EditText) findViewById(R.id.editText1);
// output1.setText(data);
Log.d("mytag", line);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
I guess you are trying to show toast on a background thread, which is not allowed in android. you can use this code to show toast in background thread :
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
});
You must display Toast only from UI thread, to workaround this you can get use of runOnUiThread() method or create new Handler and pass in constructor Looper.getMainLoopper()
You could use AsyncTask Framework to make background processing easier http://developer.android.com/reference/android/os/AsyncTask.html.
The method onPostExecute(Result) will be run on your UI thread there for you can change your UI element here.
This question already has answers here:
What is the way to run a new thread and a UI thread in Android? [closed]
(3 answers)
Closed 8 years ago.
I'm trying to write a code which signups a user. The php script is running fine. But code is android code is not working. Values not going on server.
package com.androidexample.httpgetexample;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HttpGetAndroidExample extends Activity {
TextView content;
EditText fname,email,login,pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_get_android_example);
content = (TextView)findViewById(R.id.content);
fname = (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
login = (EditText)findViewById(R.id.loginname);
pass = (EditText)findViewById(R.id.password);
Button saveme=(Button)findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
//ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Please wait, connecting to server.",
Toast.LENGTH_LONG).show();
try{
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
String fnameValue = URLEncoder.encode(fname.getText().toString(), "UTF-8");
String emailValue = URLEncoder.encode(email.getText().toString(), "UTF-8");
String passValue = URLEncoder.encode(pass.getText().toString(), "UTF-8");
HttpClient Client = new DefaultHttpClient();
String URL = "http://nishtha.comze.com/log.php?user="+loginValue+"&name="+fnameValue+
"&email="+emailValue+"&pass="+passValue;
//Log.d("httpget", URL);
try
{
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpResponse response = Client.execute(httpget);
Log.d("Http Response:", response.toString());
String SetServerString = "";
SetServerString = Client.execute(httpget, responseHandler);
content.setText(SetServerString);
}
catch(Exception ex)
{
content.setText("Fail!");
}
}
catch(UnsupportedEncodingException ex)
{
content.setText("Fail22");
}
}
});
}
}
When I run the code it olways display "Fail"
You need to use AsyncTask<> or IntentService to handle your request.
I am unable to communicate to receive and send reply between the web server(which uses flask framework) and my android app whose code is as shown below.
If possible can you please post a sample server end code which might solve my problem.
package com.project.nsj;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
String userName, passkey;
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
Button login = (Button) findViewById(R.id.login_button);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//checkLogin login = new checkLogin();
//login.execute();
Intent funcs = new Intent(MainActivity.this, Functions.class);
startActivity(funcs);
}
});
}
public class checkLogin extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
userName = username.getText().toString();
passkey = password.getText().toString();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://rpihomeautomation.no-ip.biz");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", userName));
nameValuePair.add(new BasicNameValuePair("passkey", passkey));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response;
int status = 0;
try {
response = httpClient.execute(httpPost);
status = response.getStatusLine().getStatusCode();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == 200) {
Intent funcs = new Intent(MainActivity.this, Functions.class);
startActivity(funcs);
} else {
Toast.makeText(MainActivity.this, "Invalid password/username",
Toast.LENGTH_LONG).show();
}
}
}
}
The simplest case for handling a HTTP POST request is:
from flask import Flask, request
app = Flask(__name__)
#app.route("/data", method=("POST",))
def handle_data():
return "Hello World - you sent me " + str(request.values)
if __name__ == '__main__':
app.run()
I am using oracle db and weblogic as web server.
From my android app i am able to send parameters to my remote server..
My PROBLEM is HOW TO GET THE RESULT SET GENERATED BY MY QUERY FROM MY SERVER TO MY ANDROID APP???
I would be very grateful if someone sites me some examples of doing it...
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
The code given below is my jsp page...
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.util.*,java.sql.*"%>
<%!
Connection con;
PreparedStatement ps;
String uname,pass;
ResultSet rs;
%>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl","pro","pro");
ps=con.prepareStatement("select * from login_stud");
rs=ps.executeQuery();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
I want my android app to retrieve the result set 'rs'....and display it on the mobile screen...how to do that.???. if you want details abut my app u can ask me #dldnh
The best thing you can do is to implement JSON with a RESTFUL Web Service.
More info:
JSON.ORG
How to create a JSON response
Android includes JSON classes such as JSONArray, JSONObject that can be used to interpret the response the Web Service will return. See more at here.
You can't go wrong. JSON is fast, there are ways to secure the communication if you implement RESTFUL Authentication.
Best of all your Web Service will be compatible with iOS Apps and any other platform with JSON support.
Good luck!
The code to be witten in android should be this:
package com.campuspro.start;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login_Menu extends Activity {
EditText usname;
EditText pass;
TextView tv;
HttpClient client;
HttpPost post;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_lay);
tv=(TextView) findViewById(R.id.login_stat_tv);
usname=(EditText)findViewById(R.id.uname);
pass=(EditText)findViewById(R.id.pass);
Button login=(Button)findViewById(R.id.login_but);
Button cancel=(Button)findViewById(R.id.cancel_but);
client = new DefaultHttpClient();
String url="http://10.0.2.2:7001/proj/login.jsp";//your url
post = new HttpPost(url);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
new Login().execute("");
}
});
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
usname.getText().clear();
pass.getText().clear();
}
});
}
private class Login extends AsyncTask<String, Void, JSONObject>{
ProgressDialog dialog = ProgressDialog.show(Login_Menu.this, "", "Authenticating, Please wait...");
#Override
protected JSONObject doInBackground(String... params) {
Log.i("thread", "Doing Something...");
//authentication operation
try{
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username",usname.getText().toString()));
pairs.add(new BasicNameValuePair("password",pass.getText().toString()));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
int status=response.getStatusLine().getStatusCode();
if(status == 200)
{
HttpEntity e=response.getEntity();
String data=EntityUtils.toString(e);
JSONObject last=new JSONObject(data);
return last;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPreExecute(){
//dialog.dismiss();
Log.i("thread", "Started...");
dialog.show();
}
protected void onPostExecute(JSONObject result){
Log.i("thread", "Done...");
String status;
String name;
try {
status= result.getString("status");
name=result.getString("uname");
if(dialog!=null)
{
dialog.dismiss();
}
else{}
if(status.equalsIgnoreCase("yes"))
{
tv.setText("Login Successful...");
Bundle newbundle=new Bundle();
newbundle.putString("uname",name);
Intent myIntent=new Intent(Login_Menu.this,Instruction.class);
myIntent.putExtras(newbundle);
startActivity(myIntent);
}
else{
tv.setText("No User Found, please try again!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And the server side JSP code should be:
<%#page contentType="text/html; charset=UTF-8"%>
<%#page import="org.json.simple.JSONObject"%>
<%#page import="java.util.*,java.sql.*"%>
<%!
Connection con;
PreparedStatement ps;
ResultSet rs;
String x,y;
%>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","db_username","db_password");
x=request.getParameter("username");
y=request.getParameter("password");
ps=con.prepareStatement("select * from table_name where suid=? and spwd=?");
ps.setString(1,x);
ps.setString(2,y);
rs=ps.executeQuery();
JSONObject obj=new JSONObject();
if(rs.next())
{
String uname=rs.getString(4);
obj.put("status","yes");
obj.put("uname",uname);
out.print(obj);
}
else
{
obj.put("status","no");
out.print(obj);
}
out.flush();
%>