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();
%>
Related
Hello everyone I am trying to fetch data from mysql database in android ListView,
Following code is throwing java.lang.StringIndexOutOfBoundsException
I am new to Android Development, If anybody could guide me through this it will be much help.
Thank You.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
public class Main_catagory_one extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter adapter;
ListView listProduct;
ArrayList<Product> records;
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
context=this;
records=new ArrayList<Product>();
listProduct=(ListView)findViewById(R.id.listView1);
adapter=new CustomAdapter(context, R.layout.list_view,R.id.textView3,
records);
listProduct.setAdapter(adapter);
}
public void onStart(){
super.onStart();
//execute background task
BackTask bt=new BackTask();
bt.execute();
}
//background process to make a request to server and list product information
private class BackTask extends AsyncTask<Void,Void,Void>{
protected void onPreExecute(){
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/fetch_item/getproducts.php");
response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(Exception e){
if(pd!=null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("ERROR", "Error converting result "+e.toString());
}
//parse json data
try{
// Remove unexpected characters that might be added to beginning of the string
result=result.substring(result.indexOf("["));
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data =jArray.getJSONObject(i);
Product p=new Product();
p.setpName(json_data.getString("Item_name"));
p.setuPrice(json_data.getString("Item_price"));
p.setpQauntity(json_data.getString("Item_quantity"));
p.setpImage(json_data.getString("Item_img"));
records.add(p);
}
}
catch(Exception e){
Log.e("ERROR", "Error pasting data "+e.toString());
}
return null;
}
protected void onPostExecute(Void result){
if(pd!=null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
adapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
IndexOutOfBoundsException - if beginIndex is negative or larger than
the length of this String object.
You should get used to using the API. It tells you what exceptions a method throws and why.
Try printing length of the string before and after doing substring.
For example...
String testing = "Hello World";
System.out.println("Length of testing = " + testing.length);
System.out.println("Value of testing = " + testing);
testing.substring(1,2);
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/
I am trying to make an app where i am supposed to send data from the application to a web server.
So far i've been searching and not been able to find a working example, i've found some using asynctask which does not work, so any help is appreciated!
try below code :-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
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.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
etTwitter = (EditText) findViewById(R.id.etTwitter);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else if(etTwitter.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
see below link for more info :-
http://hmkcode.com/android-send-json-data-to-server/
http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89
Try this,
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.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class AdminLogin extends Activity {
EditText adminUN, adminPass;
CheckBox cb;
Button loginBtn;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
// Your IP address or your website complete address
String adminLoginURL = "http://192.168.1.1/admin_login.php";
ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_login);
loginBtn = (Button) findViewById(R.id.adminLogin);
adminUN = (EditText) findViewById(R.id.adminUName);
adminPass = (EditText) findViewById(R.id.adminPass);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Admin_Login().execute();
}
});
}
class Admin_Login extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(AdminLogin.this);
dialog.setMessage("Please Wait..!");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
protected String doInBackground(String... params) {
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
dialog.dismiss();
}
}
void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(adminLoginURL);
// add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", adminUN
.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password", adminPass
.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
boolean matches = response.startsWith("User Found");
if (matches) {
// Do something start an Activity or do anything you wanted
}
} else {
showAlert();
}
} catch (Exception e) {
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert() {
AdminLogin.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(
AdminLogin.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_exit, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Create an .xml file to get the username, password, and login button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_wall"
android:gravity="center_horizontal"
android:orientation="vertical" >
<EditText
android:id="#+id/adminUName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="50dip"
android:hint="Username"
android:singleLine="true" />
<requestFocus />
<EditText
android:id="#+id/adminPass"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
<Button
android:id="#+id/adminLogin"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dip"
android:text="Login"
android:textColor="#0b84aa" />
</LinearLayout>
You must have PhpMyAdmin to try this in local system, if you have hosted server part then try use the following php code and run it.
adminLogin.php
<?php
$hostname_localhost ="";
$database_localhost ="";
$username_localhost ="";
$password_localhost ="";
# Make sure above fields are filled with your config values (must)
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
if (empty($_POST['username'])) {
echo "Please Enter a name";
} else {
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
echo "Please Enter Your Password ";
} else {
$password = SHA1($_POST['password']);
}
$query_search = "select * from adminregister where username = '".$username."' AND password = '".$password."'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "\nNo Such User Found";
}
else {
echo "User Found";
}
mysql_close();
?>
Note: You need to create database and table specified in mysql to feed and retrieve the data
If any errors please leave a comment.
I just build a demo application through async task and now i want the json data in list view so i dont know where i can add json functions and array list etc so plz guide me or help me by edit the code i thankful in advance and plz help im new to android and java
package your.packag.namespace;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
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;
public class runActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}}
You can use the built-in org.json classes to convert the retrieved string (your text variable content) in to JSON objects.
Have a look at the tutorial from Lars Vogel on how to do that.
I am working on with:
org.apache.http.HttpResponse;
org.apache.http.client.HttpClient;
org.apache.http.client.methods.HttpGet;
org.apache.http.impl.client.DefaultHttpClient;
i am using jsp for writing server side code.
i am unaware of the procedure of sending some value to server from my emulator.
and get a value o a string from the server response.
I mean to say... what are the methods to be used? How to use them.?
To send a HTTP GET request and retrieve response:
private static void get(final Context context, final String url) {
new Thread() {
#Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet request = Utils.createHttpRequest(context, url, true, false);
setProxyIfNecessary(context, request);
try {
HttpResponse response = client.execute(request);
Log.v("Test", "StatusCode: " + response.getStatusLine().getStatusCode() + ", Entity: " + EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
// Oh, crash
}
}
}.start();
}
private static void setProxyIfNecessary(Context context, HttpUriRequest request) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivity == null ? null : connectivity.getActiveNetworkInfo();
if (networkInfo == null || networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return;
}
String proxyHost = Proxy.getHost(context);
if (proxyHost == null) {
return;
}
int proxyPort = Proxy.getPort(context);
if (proxyPort < 0) {
return;
}
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
}
Call it by:
get(context, "http://developer.android.com/index.html");
And you will get log by logcat *:S Test:V
Notice that the new thread is to avoid blocking UI thread
Below is a code i implemented for sending username and password from android to server side JSP page. The response from the server is a json object which is then processed.The code is as given below.
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";
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();
}
}
}
}