My application is passing two value from device to remote server but it work in when i tested in bluestack when I install in real device it show a message like "Unfortunately app has been stooped" so I can't under stand where is problem i delete and clean device temporary and cache memory of device still not getting output.
following is my source code
package com.androidexample.httpgetexample;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class HttpGetAndroidExample extends Activity {
TextView content;
EditText fname,email,login,pass;
Spinner sp;
Button b1;
String s[] = { "Courtage Problem", "Cartage Refil", "Printer Problem",
"Printer Drivers" };
#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);
sp = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> ad = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, s);
sp.setAdapter(ad);
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
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 n = URLEncoder.encode(fname.getText().toString(), "UTF-8");
String d = URLEncoder.encode(sp.getSelectedItem().toString(), "UTF-8");
HttpClient Client = new DefaultHttpClient();
String URL = "http://shreebijapur.in/Customerquery.aspx?n="+n+"&d="+d;
//Log.i("httpget", URL);
try
{
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String SetServerString = "";
SetServerString = Client.execute(httpget, responseHandler);
content.setText(SetServerString);
}
catch(Exception ex)
{
content.setText("Fail!");
}
}
catch(UnsupportedEncodingException ex)
{
content.setText("Fail111");
}
}
});
}
}
It's probably crashing due to the networkOnMainThreadException. I'm trying to executr an http request in an inner class that extends class AsyncTask.
I put all network related stuff in the doInBackground() method.
If Error: networkOnMainThreadException
Perform http request execution in an inner class that extends the class AsyncTask.
or
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// HERE_YOUR_HTTP_REQUEST CODE
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.execute();
Try this
Or
You can use volley, retrofit or other networking library's for API call.
Related
Trying to use the Oauth authorization flow in an andoid app using java. No browser opened needed for authorizing. I don't know if i should ask here or on the api's website
permission for internet is granted in manifest.xml
MainActivity.java:
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button RankConfirm = findViewById(R.id.UsernameConfirm);
RankConfirm.setOnClickListener(v -> {
final EditText username_box = findViewById(R.id.OsuUsername);
final String Username = username_box.getText().toString();
final TextView RankView = findViewById(R.id.RankView);
API_Response.UpdateRank(Username,RankView);
});}
}
API.java
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class API {
public static void UpdateRank(String Username, TextView RankView) {
Thread NetworkThread = new Thread ("NetworkThread"){
private volatile String Rank = "nic";
public void run() {
OkHttpClient client1 = new OkHttpClient();
Request request1 = new Request.Builder()
.url("https://osu.ppy.sh/oauth/authorize/?client_id=14403&redirect_uri=https://google.com&response_type=code&scope=public")
.build();
try {
Response response1 = client1.newCall(request1).execute();
String Code = response1.body().string();
Log.e("Debug", Code);
} catch (IOException e) {
Log.e("Debug", "IO exception1");
}```
Realized i was doing it completly wrong and i should have used a WebView
I am fairly new to Android Dev and I created a Google Form and wanted to implement the form on my app and I heard about the open source okhttp from Square Open Source, which you most likely know
So, I created a layout with the labels, gave them the same IDs and everything...
I created a java class called Form and inserted all the code, and no errors whatsoever.
(Worth mentioning I am using navigation drawer activity, don't know if that influences or not though)
So after implementing and correcting everything there was to correct, I ran the application but it just doesnt do anything. It does not do the validation nor it sends the response.
I would really appreciate if anyone could help me out with this
I will leave the code here
Once again, thanks.
package com.example.eduardobastos.testapp;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Form extends AppCompatActivity {
public static final MediaType FORM_DATA_TYPE
= MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
//URL derived from form URL
public static final String URL="https://docs.google.com/forms/d/e/1FAIpQLSeZp9wjprZJ3OR2SkIHHsZE9yDBAVnC7mO8hPKSzwGuYhqmdw/formResponse";
//input element ids found from the live form page
public static final String EMAIL_KEY="entry_943499687";
public static final String SUBJECT_KEY="entry_2058392291";
public static final String MESSAGE_KEY="entry_1420026128";
private Context context;
private EditText emailEditText;
private EditText subjectEditText;
private EditText messageEditText;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.form_layout);
//save the activity in a context variable to be used afterwards
context =this;
//Get references to UI elements in the layout
Button sendButton = (Button)findViewById(R.id.sendButton);
emailEditText = (EditText)findViewById(R.id.emailEditText);
subjectEditText = (EditText)findViewById(R.id.subjectEditText);
messageEditText = (EditText)findViewById(R.id.messageEditText);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Make sure all the fields are filled with values
if(TextUtils.isEmpty(emailEditText.getText().toString()) ||
TextUtils.isEmpty(subjectEditText.getText().toString()) ||
TextUtils.isEmpty(messageEditText.getText().toString()))
{
Toast.makeText(context,"All fields are mandatory.",Toast.LENGTH_LONG).show();
return;
}
//Check if a valid email is entered
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(emailEditText.getText().toString()).matches())
{
Toast.makeText(context,"Please enter a valid email.",Toast.LENGTH_LONG).show();
return;
}
//Create an object for PostDataTask AsyncTask
PostDataTask postDataTask = new PostDataTask();
//execute asynctask
postDataTask.execute(URL,emailEditText.getText().toString(),
subjectEditText.getText().toString(),
messageEditText.getText().toString());
}
});
}
//AsyncTask to send data as a http POST request
private class PostDataTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... contactData) {
Boolean result = true;
String url = contactData[0];
String email = contactData[1];
String subject = contactData[2];
String message = contactData[3];
String postBody="";
try {
//all values must be URL encoded to make sure that special characters like & | ",etc.
//do not cause problems
postBody = EMAIL_KEY+"=" + URLEncoder.encode(email,"UTF-8") +
"&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject,"UTF-8") +
"&" + MESSAGE_KEY + "=" + URLEncoder.encode(message,"UTF-8");
} catch (UnsupportedEncodingException ex) {
result=false;
}
try{
//Create OkHttpClient for sending request
OkHttpClient client = new OkHttpClient();
//Create the request body with the help of Media Type
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//Send the request
Response response = client.newCall(request).execute();
}catch (IOException exception){
result=false;
}
return result;
}
#Override
protected void onPostExecute(Boolean result){
//Print Success or failure message accordingly
Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show();
}
}
}
Just tested this, and works like a charm...
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import butterknife.BindView;
import butterknife.ButterKnife;
import mx.com.iisi.staffing.R;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onResume() {
super.onResume();
new PostDataTask(this).execute("","testing#testing.com","Testing","Testing message");
}
private class PostDataTask extends AsyncTask<String, Void, Boolean> {
public final MediaType FORM_DATA_TYPE
= MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
//URL derived from form URL
public static final String URL="https://docs.google.com/forms/d/e/1FAIpQLSeZp9wjprZJ3OR2SkIHHsZE9yDBAVnC7mO8hPKSzwGuYhqmdw/formResponse";
//input element ids found from the live form page
public static final String EMAIL_KEY="entry_943499687";
public static final String SUBJECT_KEY="entry_2058392291";
public static final String MESSAGE_KEY="entry_1420026128";
private Context context;
public PostDataTask(Context context)
{
this.context = context;
}
#Override
protected Boolean doInBackground(String... contactData) {
Boolean result = true;
String url = contactData[0];
String email = contactData[1];
String subject = contactData[2];
String message = contactData[3];
String postBody="";
try {
//all values must be URL encoded to make sure that special characters like & | ",etc.
//do not cause problems
postBody = EMAIL_KEY+"=" + URLEncoder.encode(email,"UTF-8") +
"&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject,"UTF-8") +
"&" + MESSAGE_KEY + "=" + URLEncoder.encode(message,"UTF-8");
} catch (UnsupportedEncodingException ex) {
result=false;
}
try{
//Create OkHttpClient for sending request
OkHttpClient client = new OkHttpClient();
//Create the request body with the help of Media Type
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder()
.url(URL)
.post(body)
.build();
//Send the request
Response response = client.newCall(request).execute();
}catch (IOException exception){
result=false;
}
return result;
}
#Override
protected void onPostExecute(Boolean result){
Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show();
}
}
}
I'm making an Android application wherein a student logs in with his registration ID then can access services like view his grades, class schedule, etc. without entering his registration ID twice.
My question here is, how can I get the registration ID he first entered during login and use it to access other activities so that he would not have to enter again?
Here's is the code for the login activity:
package com.example.kreshiathea.myfirstapp;
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.os.Bundle;
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;
public class MainActivity2 extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
b = (Button)findViewById(R.id.loginnext);
et = (EditText)findViewById(R.id.rfid);
tv = (TextView)findViewById(R.id.tv);
String rfid = et.getText().toString().trim();
Intent in = new Intent(getApplicationContext(), MainActivity3Activity.class);
in.putExtra("rfid", rfid);
startActivity(in);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show( MainActivity2.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://usamobileapp.pe.hu/webservice/check.php"); // make sure the url is correct.
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText( MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent( MainActivity2.this, MainActivity3Activity.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
MainActivity2.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder( MainActivity2.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();
}
});
}
}
I tried to uses an instance so I could import variable to another class. But I'm sure where to put it exactly so I placed it here:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
b = (Button)findViewById(R.id.loginnext);
et = (EditText)findViewById(R.id.rfid);
tv = (TextView)findViewById(R.id.tv);
String rfid = et.getText().toString().trim();
Intent in = new Intent(getApplicationContext(), MainActivity3Activity.class);
in.putExtra("rfid", rfid);
startActivity(in);
This is the class where I want to import the variable MainActivity3Activity
Here's the code:
package com.example.kreshiathea.myfirstapp;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity3Activity extends Activity {
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
HttpClient httpclient;
HttpGet request;
HttpResponse response;
HttpPost httppost;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://usamobileapp.pe.hu/webservice/student_info.php");
try {
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", rfid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TextView result = (TextView) findViewById(R.id.tvResult);
try {
request = new HttpGet("http://usamobileapp.pe.hu/webservice/student_info.php");
response = httpclient.execute(request);
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I place the receiving intent here:
public class MainActivity3Activity extends Activity {
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
HttpClient httpclient;
HttpGet request;
HttpResponse response;
HttpPost httppost;
List<NameValuePair> nameValuePairs;
The MainActivity3Activity class also displays the student information (using the previously entered registration ID).
I'm not sure if I correctly used and placed the intents. So please I'm looking for any help.
Call getIntent(); method to receive Intent from previous Activity in onCreate method of MainActivity3Activity Activity like :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
}
You should move
Intent in = getIntent();
String rfid = in.getStringExtra("rfid");
inside onCreate(...) method of Activity
getIntent() is available only after onCreate(...) you cant used it before onCreate(...)
Use sharedpreferences if you want to use in multiple activities
SharedPreferences preferences=getSharedPreferences("logindetails", Activity.MODE_PRIVATE);
Editor editor=preferences.edit();
editor.putString("regId", id);
editor.commit();
You can get regid as follows
id=getSharedPreferences("logindetails", Activity.MODE_PRIVATE).getString("regId",defaultValue);
Hope this will help you.
Intent intent = getIntent();
String id = intent.getStringExtra("regId");
Using this id you can get all the details in the next activity.
You could store the registration as a static variable, which means it will maintain its value and you can access it from anywhere. I've done this loads of times in my own code and it's really handy.
For example, you could create a class called Globals or something, and in this class have your registration number.
public class Globals {
public static String registrationNumber;
// Or make a nice getter and setter for this :)
}
...so when you get the number from the user's input, set this variable:
Globals.registrationNumber = registrationNumber;
...then get it from this class when you need it later:
String registrationNumber = Globals.registrationNumber;
It's best to only use this for small things like this. If you keep massive objects in static variables, it means that object will continue to use memory throughout your app's lifecycle. Unless you are using something often, or the object is small (like your reg number), I wouldn't do this, as it is an unnecessary use of memory.
The other answers about passing the registration number between activities via the Intent is just as good an approach. It just means you have to write and read the value from the Intent extras every time. I would personally use that approach for passing an object or ID of something you have selected from a list to display it in a detail screen or something. For something that you regularly use, I'd go for the static variable approach.
Also... another thing you could do is save the registration number in the app preferences so that you can read it when the user starts the app and they don't have to log in again.
// Save the registration number to preferences.
SharedPreferences preferences = context.getSharedPreferences("MY_APP_PREFERENCES", Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("REGISTRATION_NUMBER", registrationNumber);
editor.commit();
...
// Get from preferences.
SharedPreferences preferences = context.getSharedPreferences("MY_APP_PREFERENCES", Context.MODE_PRIVATE);
String registrationNumber = preferences.getString("REGISTRATION_NUMBER", null);
// The second parameter above is the default value if nothing is returned.
Good luck!
after searching around im able to retreive a response from my servlet , but i cant send a parameter (a username and a password parameter) from android to a servlet! My logcat shows this error:
04-0java.lang.ClassCastException: org.apache.http.client.methods.HttpGet cannot be cast to org.apache.http.HttpResponse
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:76)
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
and i cant understand why!
Here it is my android main activity:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL,nameValue,passValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
Button button=(Button)findViewById(R.id.but);
try {
nameValue =URLEncoder.encode(name.getText().toString(), "UTF-8");
passValue =URLEncoder.encode(pass.getText().toString(), "UTF-8");
URL = "http://10.0.2.2:8080/login/web";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
List<NameValuePair> postParameters =
new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("user",nameValue));
postParameters.add(new BasicNameValuePair("pass",passValue));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
((HttpResponse) httpGet).setEntity(formEntity);
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
Does anyone have any idea?
UPDATE:
now i have changed my android code like this:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
Button button=(Button)findViewById(R.id.but);
try {
String nameValue ="user="+URLEncoder.encode(name.getText().toString(), "UTF-8");
String passValue ="&pass="+URLEncoder.encode(pass.getText().toString(), "UTF-8");
URL = "http://10.0.2.2:8080/login/web?"+nameValue+passValue;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
this time runs without logcat errors but the parameters does not come to the servlet!
Looking at the stack trace, I guess your problem is at this line.
((HttpResponse) httpGet).setEntity(formEntity);
Why are you casting it to HttpResponse?
OK. You want to send user/pass parameters using HTTP GET. For HTTP GET, all parameters are part of the URL. Maybe this can give you some help on how to perform a HTTP GET and pass parameters in. But in general, URL would look like this
http://www.blah.com/servlet?user="1234"&pass="password"
The stuff after the ? in the URL contains all the parameters. But there is a length limit in the URL, if you exceed that length, you'll have to use HTTP POST.
Try this link to see if it can help you
http://androidexample.com/How_To_Make_HTTP_Get_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=63&aaid=88
i have modified the activity and the problem was that the URL and nameValue and passValue was declared on the wrong section of the code ! Here it is the right android code:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
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 MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL,nameValue,passValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
content.setText("Vendosni Perdoruesin dhe Fjalekalimin");
Button button=(Button)findViewById(R.id.but);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameValue="&user="+name.getText().toString();
passValue ="&pass="+pass.getText().toString();
URL = "http://10.0.2.2:8080/login/web2?activitetiNR=1"+nameValue+passValue;
AsyncTaskRunner runner = new AsyncTaskRunner();
Log.i("url",URL);
Log.i("url",nameValue);
Log.i("url",passValue);
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
I am trying to get an Android device to send some HTTP request using GET method.
Here is my code:
package com.kde.httprequest;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
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.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class main2 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edit1 = (EditText) findViewById (R.id.editText1);
Button btn1 = (Button) findViewById (R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
grabURL(edit1.getText().toString());
}
});
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(main2.this);
final TextView text1 = (TextView) findViewById (R.id.textView1);
protected void onPreExecute() {
Dialog.setMessage("Downloading source..");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(main2.this, Error, Toast.LENGTH_LONG).show();
text1.setText(Error);
} else {
Toast.makeText(main2.this, "Source: " + Content, Toast.LENGTH_LONG).show();
text1.setText(Content);
}
}
}
}
My simple PHP test:
<?php
$a = $_GET['user'];
$b = $_GET['pass'];
if ($a=="usr" && $b=="pass") {
echo "success";
} else {
echo "fail";
}
?>
My code is running smoothly when send to this URL:
digitalzone-btm.com/test2.php?user=user&pass=pass
The response from my PHP is a string say "success" or "fail", that is what I am expected.
But I am getting a different response from my local webserver with a same Android app and PHP file.
Ex url:
http://192.168.1.8/test2.php?user=user&pass=pass
The response is exactly my PHP source code.
How can I get a "success" or "fail" response from my local webserver?
It would appear your local web server doesn't have php installed or configured right. Check here for help.
PHP: Installation and Configuration - Manual