HTTP POST REQUEST To PHP Server Android Studio - android

public class MainActivity extends AppCompatActivity {
EditText editmsg , editmail ;
TextView content ;
String Message , Email ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editmsg = (EditText) findViewById(R.id.editMessage);
editmail = (EditText) findViewById(R.id.editMail);
Button btnsubmit = (Button) findViewById(R.id.btnSubmit);
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
GetText();
} catch (Exception ex) {
content.setText(" Url Exception!");
}
}
});
}
public void GetText()throws UnsupportedEncodingException {
Message = editmsg.getText().toString();
Email = editmail.getText().toString();
String data = URLEncoder.encode("message", "UTF-8")
+ "=" + URLEncoder.encode(Message, "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "="
+ URLEncoder.encode(Email, "UTF-8");
String text = "";
BufferedReader reader=null;
HttpURLConnection urlConnection = null;
try
{
// Defined URL where to send data
URL url = new URL("http://nitesh.com/feedback/add.php");
// Send POST data request
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response on activity
content.setText( text );
}
}
I dont know what is wrong with code when i click the send button it showing Unfortunately,HTTP has stop (looking just like app crashed).
please review my code and tell me what i have done wrong.

One thing I see at once is that you are making your request in main UI thread (in onCreate). This is not allowed because network connections usually take some time to finish. There should also be an error message in the logcat about this.
What you should do is make your request in a separate thread. You can accomplish this by using AsyncTask, or Thread. Google it.
UPD:
Example on how to use Threads in Java. The method run will be executed asynchronously.
new Thread(new Runnable(){
#Override
public void run(){
GetText();
}
}).start();
Next time, please include the logcat errors in the question.

Consider using http://square.github.io/retrofit/ for network communication.
You will get a simple api and all request will be wrapped into correct thread.

You can accomplish this task by using AsyncTask

Related

HttpURLConnection crashes application

I want to receive and send data with a web server but the code does not work
What do I do for this code to work?
Note this code inside onCreate
try {
URL url = new URL("http://myweb.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream Stream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(Stream);
BufferedReader b = new BufferedReader(reader);
StringBuilder s = new StringBuilder();
String str ="";
while ((str = b.readLine())!=null) {
s.append(str);
}
String data = s.toString();
TextView myText = (TextView) findViewById(R.id.Text);
myText.setText(data);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Make sure that you do network-related tasks on a separate thread in Android. Also, check that you have the INTERNET permission set.
If you want to then update the UI from another thread, you have to use
runOnUiThread (new Runnable () {
public void run() {
//update ui in here
}
}
All your code runs in Main thread which should be always used for setting up the UI and to listen for UI events such as on click listeners.
Network calls are not allowed on this thread as they might take long time. Use AsyncTask API of android which is designed for running code in separate thread.
Create a class like one below for all GET request tasks.
public class DownloadTask extends AsyncTask<String, Void, Integer> {
private String TAG = "InDownloadTask";
private DownloadCallback callback;
private String data;
public DownloadTask(DownloadCallback cb){
callback = cb;
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
data = response.toString();
result = 1;
} else {
result = 0;
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
callback.onFinishDownload(data, integer);
}
}
Create a callback interface that we use for the above class.
public interface DownloadCallback {
public void onFinishDownload(String data, Integer result);
}
Now from your activity onCreate
String url = "http://myweb.com/";
new DownloadTask(new DownloadCallback() {
public void onFinishDownload(String data, Integer result) {
if(result == 1)
myText.setText(data);
else
myText.setText("Error");
}
}).execute(url);
If you have many network related operations, use a Network library such as Volley which will take care of this.

BufferedReader does not work in Android

I have tried to use an instance of BufferReader to read a content of a web page but when running the app, it moves immediately to catch block when reaching this line:
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Could you please tell me what is the problem?
By the way, I have made a permmition to Internet connection in the mainifest file and there is no error registered in the Log cat!
this is my java code:
Thread thrd = new Thread( new Runnable() {
#Override
public void run() {
final Button btn = (Button) findViewById(R.id.btn_1);
final TextView tv = (TextView) findViewById(R.id.tv_1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
URL url = null;
url = new URL("http://www.google.com/");
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String Line = "";
while( (Line= reader.readLine() ) != null){
tv.append(Line);
}
catch (Exception e){
tv.append("There is a problem");
}
}
});
}
});
thrd.start();
return true;
}
have you tried logging the exception? something along the lines of
Log.d(TAG, "onClick", e);
in your catch block.
With that said, you are probably getting a NetworkOnMainThreadException, because you are trying to access the network on the main thread. Because network calls are blocking, this will cause the UI to freeze - which is a very bad User Experience. All network calls should be done in a separate thread (be that a Service, AsyncTask, or a Thread).
see this SO answer for more information about the NetworkOnMainThreadException

Why AsyncTask doesn't show result first time?

I have a text file on a server (right now on a local server by WAMP in c:/wamp/www/android/sample.txt ) and an android application with 3 activity that read data through the WiFi.
The first one get the address (on local host use 10.0.2.2/android/sample.txt) and go to activity2. In activity2 I have a button that goes to activity3.
code is third activity:
private InputStream OpenHttpConnection(String urlString) throws Exception {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
throw new IOException("NOT an HTTP Connection!");
}
try {
HttpURLConnection httpCon = (HttpURLConnection) conn;
httpCon.setAllowUserInteraction(false);
httpCon.setInstanceFollowRedirects(true);
httpCon.setRequestMethod("GET");
httpCon.connect();
response = httpCon.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpCon.getInputStream();
Log.d("myerr", response + "");
}
} catch (Exception e) {
Log.d("myerr2", e.getLocalizedMessage());
throw new IOException("Error Connection!");
}
return in;
}
private String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (Exception e) {
Log.d("myerr", e.getLocalizedMessage());
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String
.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (Exception e) {
Log.d("myerr", e.getLocalizedMessage());
return "";
}
return str;
}
private class DownloadTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
protected void onPostExecute(String result) {
Global.readedDataFromFile=result;
//Toast.makeText(DrawRhActivity.this,"Result: "+Global.readedDataFromFile, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_rh);
String user_address = Global.ip_address;
new DownloadTextTask().execute(user_address);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Value: " + Global.readedDataFromFile);
}
I also define some global variable in Global.java .
AND HERE IS MY PROBLEM:
The 3rd activity doesn't show data on textview at the first time. but when I back to 2nd activity and hit the button my data loaded.
Why AsyncTask doesn't show result first time and how to fix this?
Thanks for your attention.
tv.setText("Value: " + Global.readedDataFromFile);
write this line in onPostExecute
protected void onPostExecute(String result) {
Global.readedDataFromFile=result;
//Toast.makeText(DrawRhActivity.this,"Result: "+Global.readedDataFromFile, Toast.LENGTH_LONG).show();
tv.setText("Value: " + Global.readedDataFromFile);
}
Solution:
put tv.setText("Value: " + Global.readedDataFromFile); in your onPostExecute method.
Explaination:
AsyncTask runs on separate thread instead of your UI thread.
so when it is being executed Global.readedDataFromFile may be empty.and when execution completes it goes in onPostExecute method and now Global.readedDataFromFile have some value stored in it.
Issue:
you are setting the text instantly after calling new DownloadTextTask().execute(user_address);
so it may happen that the AsyncTask is not completed yet and Global.readedDataFromFile is empty.
Reference:
AsyncTask
I hope it will be helpful !!
the problem lies within your onCreate function:
String user_address = Global.ip_address;
new DownloadTextTask().execute(user_address);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Value: " + Global.readedDataFromFile);
First you start a task, then you want to set your views, but your task is not finished.
You have to set the views with the result of your task in to onPostExecute of the task.
Keep your DownloadTextTask &
Trying this code in your Activity
DownloadTextTask textTask = new DownloadTextTask();
textTask.execute(user_address);
String strDownloaded = "";
try {
strDownloaded = textTask.get();
} catch (Exception e) {
Log.e("DownloadTextTask", "Error: " + e.getMessage());
}

How to Get Specific Information From the Internet In Android App

im pretty new In Android App development, I need some help.
Im creating this simple dictionary application that prompts the user to enter a word and after a button press it will take that word to the internet, probably wikipedia.org and return that information to the User.
I used XML to develop the app textfield and button. And created a piece of text (ansa) which will be set to whatever the answer is using the OnClickListener,
I do not want to set up a webview
I just want the text to be set to the dictionary answer.
Here's what i have been able to do so far. There is this class to get data from google.
public class GetMethod {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.google.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in !=null){
try{
in.close();
return data;
}catch(Exception e){
e.printStackTrace();
}
}
}
}
And Another class where the XML is implemented
public class Dictionary extends Activity {
TextView ansa;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary);
Button Search = (Button) findViewById(R.id.search);
ansa = (TextView) findViewById(R.id.ansa);
final GetMethod test = new GetMethod();
Search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String returned;
try {
returned = test.getInternetData();
ansa.setText(returned);
} catch (Exception e) {
ansa.setText("Failed");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
When it executes I get the whole website's HTML
So I need help on how to take the user's word to the wiki website, and get only the text of the ansa, probably parse and store it to some string.
Thank You Alot.
You can use an API like Google Dictionary or dictionary.com.
But you will have to implement the HTTP client and parse the response. And then show the desired data .

getting the html source code with a url in an android application

I was trying to write some codes that takes in a url from the user and after which when the submit button is clicked, I will take the url and make a call and retrieve the html source code from the page. However, I have gotten a exception of the following:
W/System.err(14858): android.os.NetworkOnMainThreadException
W/System.err(14858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
It seems that for android 3.0 the platform that I am trying to development on doesn't allow me to use the network resources on the main method. I understand that there are methods such as running it in the background or use the async method should work, but can anyone guide me on this? I'm not too sure on how to go about it. I'm new to programming.
Thanks in advance.
Below is my current code, on the onclick method:
String htmlCode = "";
try {
URL url = new URL("http://www.google.com");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode += inputLine;
Log.d(LOG_TAG, "html: " + inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Error: " + e.getMessage());
Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
}
You could use a Runnable or Thread, but probably the most idiomatic Android way to do this is to use an AsyncTask.
new AsyncTask<String, Void, String>(){
#Override
protected String doInBackground(String... urlStr){
// do stuff on non-UI thread
StringBuffer htmlCode = new StringBuffer();
try{
URL url = new URL(urlStr[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode += inputLine;
Log.d(LOG_TAG, "html: " + inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Error: " + e.getMessage());
Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
}
return htmlCode.toString();
}
#Override
protected void onPostExecute(String htmlCode){
// do stuff on UI thread with the html
TextView out = (TextView) findViewById(R.id.out);
out.setText(htmlCode);
}
}.execute("http://www.google.com");

Categories

Resources