I have an activity with 2 EditText.
When the user is clicking on the Send button, I want to send EditText value to my server.
i tried to make a POST request when the user clicking on the button.
The problem is when the user is clicking on the button He get a error, and the application closing automatically.
This is my code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class register extends AppCompatActivity {
private EditText nameE,l_nameE;
private Button registerE;
private String name,l_name,token;
boolean thread_running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
FirebaseMessaging.getInstance().subscribeToTopic("test");
token = FirebaseInstanceId.getInstance().getToken();
Toast.makeText(this, token, Toast.LENGTH_LONG).show();
final Button register = (Button)findViewById(R.id.button);
nameE = (EditText)findViewById(R.id.editText);
l_nameE = (EditText)findViewById(R.id.editText2);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerToken();
}
});
}
public void intialize(){
name = nameE.getText().toString().trim();
l_name = l_nameE.getText().toString().trim();
}
public boolean validate(){
boolean e=true;
if(name.equals("")){
e=false;
nameE.setError("enter name");
}else if(l_name.equals("")){
e=false;
l_nameE.setError("enter l_name");
}
return e;
}
private void registerToken() {
intialize();
if (!validate()) {
Toast.makeText(this, "err", Toast.LENGTH_LONG).show();
}else{
reg();
}
}
public void reg(){
Toast.makeText(this, "reg", Toast.LENGTH_LONG).show();
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("name",name)
.add("l_name",l_name)
.build();
Request request = new Request.Builder()
.url("http://192.168.0.106/fcm/register.php")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
thank you
You are doing a network call on the main thread. That is not allowed on Android as it will block your whole application until the request is completed.
A solution will be to wrap your network call in an AsyncTask for example.
But as you are using OKHttpClient, they are offering an async api for such things.
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
//something went wrong
Log.e(YOUR_TAG, e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Response not sueccessful " + response);
}
//success do whatever you want. for example -->
Log.d(YOUR_TAG, response.body().string());
}
}
So in your example instead of an synchronous call like
client.newCall(request).execute();
you have to use the async callback version like shown above.
hopefully that helps
Edit: For more recipes take a look at the wiki page: https://github.com/square/okhttp/wiki/Recipes
Related
I am currently programming an app in android studio and right now I am trying to get a stock Symbol from the user and print out the current price of the stock.So i made this:
package com.example.finalproject;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.loopj.android.http.*;
import androidx.appcompat.app.AppCompatActivity;
import cz.msebera.android.httpclient.Header;
import android.widget.EditText;
import android.view.inputmethod.EditorInfo;
import android.text.InputType;
public class StockPriceActivity extends AppCompatActivity {
private EditText mStockPriceEditText;
private TextView mStockPriceTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stock_price);
mStockPriceEditText = findViewById(R.id.stock_price_edit_text);
mStockPriceTextView = findViewById(R.id.stock_price_text_view);
mStockPriceEditText.setInputType(InputType.TYPE_CLASS_TEXT);
mStockPriceEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
mStockPriceEditText.requestFocus();
mStockPriceEditText.setOnEditorActionListener((v, actionId, event) -> {
Log.d("YYYYY", "!!!!!!!!");
// Initialize the HTTP client
AsyncHttpClient client = new AsyncHttpClient();
// Set the API key
String apiKey = getString(R.string.alpha_vantage_api_key);
Log.d("YYYYY", "!!");
if (actionId == EditorInfo.IME_ACTION_DONE) {
Log.d("YYYYY", "!!!");
String stockSymbol = mStockPriceEditText.getText().toString();
// Set the URL for the API request
String url = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=" + stockSymbol + "&apikey=" + apiKey;
// Make the request
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// The request was successful.
String response = new String(responseBody);
// Parse the JSON response to get the stock price
String stockPrice = StockPriceParser.parseStockPriceFromJSON(response);
// Update the TextView with the stock price
mStockPriceTextView.setText(stockPrice);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// The request failed. Handle the error.
Log.d("YYYYY", "Everything went wrong when you see this!"); //TODO
}
});
return false;
}
return true;
});
}
}
My problem is that the ActionListener never gets triggerd, even when the user provides some input.This is the corresponding xml code:
<EditText
android:id="#+id/stock_price_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text here"
android:imeOptions="actionDone"
android:inputType="textCapSentences"
/>
I tried the hole thing without userinput by directly implementing the stockSymbol in the url, for example "AAPL" and it worked fine, so no problem with that.
In case someone is interested how I solved my problem:
package com.example.finalproject;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.loopj.android.http.*;
import androidx.appcompat.app.AppCompatActivity;
import cz.msebera.android.httpclient.Header;
import android.widget.EditText;
import android.widget.Button;
public class StockPriceActivity extends AppCompatActivity {
private EditText mStockPriceEditText;
private TextView mStockPriceTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stock_price);
mStockPriceEditText = findViewById(R.id.stock_price_edit_text);
mStockPriceTextView = findViewById(R.id.stock_price_text_view);
Button button = findViewById(R.id.button2);
button.setOnClickListener((view) -> {
// Initialize the HTTP client
AsyncHttpClient client = new AsyncHttpClient();
// Set the API key
String apiKey = getString(R.string.alpha_vantage_api_key);
if (view.getId() == R.id.button2) {
String stockSymbol = mStockPriceEditText.getText().toString();
// Set the URL for the API request
String url = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=" + stockSymbol + "&apikey=" + apiKey;
// Make the request
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// The request was successful.
String response = new String(responseBody);
// Parse the JSON response to get the stock price
String stockPrice = StockPriceParser.parseStockPriceFromJSON(response);
// Update the TextView with the stock price
mStockPriceTextView.setText(stockPrice);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// The request failed. Handle the error.
Log.d("YYYYY", "Everything went wrong when you see this!"); //TODO
}
});
}
});
}
}
I used a button, which the user has to click to submit his input. So i could use OnClickListener instead to run the code
Button button = findViewById(R.id.button2);
button.setOnClickListener((view) -> {
Hello Guys I received a a big problem in my project. I make the OkHttp request i receive response from server all is perfect. the problem is why i can't display data, i made a model item in xml and listview(this is the required view) and when i acces the page is blank.
Can anyone help me with this issue?
code for page is the following:
package com.example.socceraplication;
import static android.content.ContentValues.TAG;
import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.NonNull;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.util.ArrayList;
public class TeamInfo extends AppCompatActivity {
private ListView lv;
ArrayList<HashMap<String, String>> resultList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_info);
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(TeamInfo.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/team?name=Liverpool")
.get()
.addHeader("X-RapidAPI-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.addHeader("X-RapidAPI-Host", "heisenbug-premier-league-live-scores-v1.p.rapidapi.com")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
call.cancel();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
String jsonStr=response.body().string();
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray records = jsonObj.getJSONArray("records");
// looping through All items
for (int i = 0; i < records.length(); i++) {
JSONObject c = records.getJSONObject(i);
String league = c.getString("league");
String season = c.getString("season");
String name = c.getString("name");
String officialName = c.getString("officialName");
String address = c.getString("address");
String telephone = c.getString("telephone");
String fax = c.getString("fax");
String website = c.getString("website");
String founded = c.getString("founded");
String teamSize = c.getString("teamSize");
String averageAge = c.getString("averageAge");
String foreigners = c.getString("foreigners");
String nationaTeamPlayers = c.getString("nationaTeamPlayers");
String teamValue = c.getString("teamValue");
String venue = c.getString("venue");
String venueCapacity = c.getString("venueCapacity");
HashMap<String, String> result = new HashMap<>();
// adding each child node to HashMap key => value
result.put("league",league);
result.put("season",season);
result.put("name",name);
result.put("officialName",officialName);
result.put("address",address);
result.put("telephone",telephone);
result.put("fax",fax);
result.put("website",website);
result.put("founded",founded);
result.put("teamSize",teamSize);
result.put("averageAge",averageAge);
result.put("foreigners",foreigners);
result.put("nationaTeamPlayers",nationaTeamPlayers);
result.put("teamValue",teamValue);
result.put("venue",venue);
result.put("venueCapacity",venueCapacity);
resultList.add(result);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(TeamInfo.this, resultList,
R.layout.list_item_team, new String[]{ "league","season","name","officialName","address","telephone","fax","website","founded","teamSize","averageAge","foreigners","nationaTeamPlayers","teamValue","venue","venueCapacity"},
new int[]{R.id.league, R.id.season,R.id.name,R.id.officialName,R.id.address,R.id.telephone,R.id.fax,R.id.website,R.id.founded,R.id.teamSize,R.id.averageAge,R.id.foreigners,R.id.nationaTeamPlayers,R.id.teamValue,R.id.venue,R.id.venueCapacity});
lv.setAdapter(adapter);
}
}
}
The enqueue call is asynchronous, which means it queues up work to be run in the background at some point in the future, and when it is complete then it runs the callback you supply (onResponse). This means in your case the order of calls is
Start doInBackground
Add your Http call to the queue
Return from doInBackground
Run onPostExecute
Post empty list to the adapter
... some time later ...
Run the onResponse callback when it gets data
To fix this, you can remove the async task entirely and just queue the work from the main thread, since it already handles actually doing the request in the background.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_info);
resultList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
startRequest();
}
private void startRequest() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//...
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
call.cancel();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) {
showResult(response);
}
});
}
private void showResult(Response response) {
// show the result here - no need to runOnUiThread
// set the adapter, put text in views, etc from in here
}
If you really want to make the call from your own AsyncTask in the background, you should use the synchronous API, not the asynchronous API. This means calling execute instead of enqueue, like this:
// this MUST run on a background thread or it will block the UI thread
Response response = client.newCall(request).execute();
Hello me and my group from university decide to create an app, that a client of a gym can see his/her exercise list and we are using retrofit to get a json. Early this code was working very well, but suddenly stopped to work, and now I'm getting null response and status 200 from callback.
image with the log.d 200 and null response
Sorry for my english.
My JSON
{
"0":{
"id":"1",
"nome":"Fernanda Kondrat",
"peso":"67.4",
"altura":"172",
"imc":"22.8",
"login":"fefe",
"senha":"1234"},
"lista_exercicios":[
{
"id":"1",
"id_aluno":"1",
"nome":"supino reto",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"2",
"id_aluno":"1",
"nome":"agachamento hack",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"3",
"id_aluno":"1",
"nome":"barra fixa",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"4",
"id_aluno":"1",
"nome":"leg press",
"num_serie":"4",
"num_repeticao":"10"
}
]
}
And now my MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.u9.fabapp.virtualgym.APIClient;
import com.u9.fabapp.virtualgym.RespostaLogin;
import com.u9.fabapp.virtualgym.Resposta;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MainActivity extends AppCompatActivity {
Button btn_login;
EditText edt_login;
EditText edt_senha;
private Callback<RespostaLogin> respostaCallback;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_login = findViewById(R.id.btn_login);
edt_login = findViewById(R.id.edt_Login);
edt_senha= findViewById(R.id.edt_Senha);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d(TAG, "onClick: ");
//Intent i = new Intent(MainActivity.this, ProfileActivity.class);
//startActivity(i);
String login = edt_login.getText().toString();
String senha = edt_senha.getText().toString();
if(TextUtils.isEmpty(login)|| TextUtils.isEmpty(senha)) {
Toast.makeText(MainActivity.this, "Campos vazios", Toast.LENGTH_SHORT).show();
} else {
configurarCallback();
//new APIClient().getRestService().setUsuarioLoginDTO(login, senha, respostaCallback);
new APIClient().getRestService().setUsuarioLoginDTO(login, senha, respostaCallback);
}
}
});
}
private void configurarCallback() {
respostaCallback = new Callback<RespostaLogin>() {
#Override
public void success(RespostaLogin resposta, Response response) {
Log.d(TAG, "Funcionou: "+ response.getStatus());
Log.d(TAG, "Funcionou: " + resposta.getRETORNO());
/*if (resposta.getRETORNO().equals("SUCESSO")){
Intent intent1 = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent1);
}else{
Toast.makeText(MainActivity.this, resposta.getRETORNO() +" ,Verifique usuário e senha" , Toast.LENGTH_SHORT).show();
}*/
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(MainActivity.this, "Deu Ruim: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
};
}
}
APIClient.java
import com.u9.fabapp.virtualgym.Resposta;
import com.u9.fabapp.virtualgym.RespostaLogin;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.http.GET;
import retrofit.http.Query;
import retrofit.http.Path;
public class APIClient {
private static RestAdapter REST_ADAPTER;
public APIClient(){
createAdapterIfNeeded();
}
private static void createAdapterIfNeeded() {
if(REST_ADAPTER == null){
REST_ADAPTER = new RestAdapter
.Builder()
.setEndpoint("http://golfetto.16mb.com/virtual-fit/home/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient())
.build();
}
}
public RestServices getRestService(){
return REST_ADAPTER.create(RestServices.class);
}
public interface RestServices{
#GET("/getExercicios.php")
void setUsuarioLoginDTO(
#Query("LOGIN") String login,
#Query("SENHA") String senha,
Callback<RespostaLogin> callbackResposta
);
}
}
In interface "RestService", change at:
#GET("/getExercicios.php")
Modify it as:
#GET("getExercicios.php")
Remove "/" because it is being already being appended.
Thanks and happy coding
The full URL of your service will be
BASE_URL (defined at the time of createing retrofit object) + END_POINT_URL (defined in the interface)
You have added "http://golfetto.16mb.com/virtual-fit/home/" as base URL and in the interface you have define the endpoint as "/getExercicios.php" so the full URL will be
"http://golfetto.16mb.com/virtual-fit/home//getExercicios.php"
which is not a valid URL. So you have to remove '/' from the interface
The interface will be
public interface RestServices{
#GET("getExercicios.php")
void setUsuarioLoginDTO(
#Query("LOGIN") String login,
#Query("SENHA") String senha,
Callback<RespostaLogin> callbackResposta
);
}
When I'm trying to send post request using OkHttp, the app on my phone (LG g3) crashes without an error.
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "login=test&pasword=test");
Request request = new Request.Builder()
.url("http://myUrl")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
txtRequest.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
What am I doing wrong?
you are executing the network call on main thread, this is the exception i guess you are getting. Use AsyncTask and your problem is solved. here is corrected version of your code.
Edited
package com.example.nisu.postrequest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class SendPost extends AppCompatActivity {
Button btnSend;
TextView txtRequest;
OkHttpClient client = new OkHttpClient();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_post);
btnSend = (Button) findViewById(R.id.btnSend);
txtRequest = (TextView) findViewById(R.id.txtRequest);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Request request = new Request.Builder()
.url("http://httpbin.org/ip").get()
.build();
new MyAsyncTask().execute(request);
}
});
}
class MyAsyncTask extends AsyncTask<Request, Void, Response> {
#Override
protected Response doInBackground(Request... requests) {
Response response = null;
try {
response = client.newCall(requests[0]).execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(Response response) {
super.onPostExecute(response);
try {
txtRequest.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
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