I am new to android . I am troubling during 2 weeks with an simple android apps which I am developing. In my app , I am trying to fetch a simple text from php . But every time when I try to launch the app it crashed. My code is below
package com.example.test;
import java.io.IOException;
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.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logger.net46.net/android/hello.php");
try {
HttpResponse response = httpclient.execute(httppost);
final String str = EntityUtils.toString(response.getEntity());
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(str);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I can not finding out where is my problem. Please someone help me.
You are probably getting NetWorkOnMainThreadException. You should use a Thread or AsyncTask for making the http post request and update ui on the ui thread.
Example:
public class MainActivity extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... params) {
String str = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logger.net46.net/android/hello.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
tv.setText(result);
}
}
}
Snap
Related
I was trying to load a web page on the emulator. I was trying the following code.
package com.test.scraptest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadWebPageTask 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();
Log.e("MYAPP", "exception", e);
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
// new Toast(getApplicationContext());
Toast ts=Toast.makeText(this, "this is a message",Toast.LENGTH_SHORT) ;
ts.show();
task.execute(new String[] { "http://www.google.com" });
}
}
Problem is, when I run the application I get the following error.
" In android i'm trying to read username and password from mysql database and displaying the next window using the 'intent' "
There are two activities, the main activity and the userpage.class the first one will verify the username and password and using the 'intent' it will call the second 'userpage'
import package com.example.loginform;
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 org.apache.http.protocol.HTTP;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
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 MainActivity extends Activity implements OnClickListener {
Button login;
EditText username,password;
TextView status;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
TextView tv;
List<NameValuePair> nameValuePairs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
}
private void setup() {
// TODO Auto-generated method stub
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button)findViewById(R.id.login);
status = (TextView)findViewById(R.id.tvstatus);
tv = (TextView)findViewById(R.id.editText1);
login.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.login:
login();
break;
}
}
private void login() {
// TODO Auto-generated method stub
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("localhost/android/index.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username",username.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",password.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
ResponseHandler<String>responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,responseHandler);
tv.setText(""+response);
if(response.equalsIgnoreCase("User Found"))
{
startActivity(new Intent(this,UserPage.class));
}
}catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(),"Sorry error in the connection!!",Toast.LENGTH_SHORT).show();
}
}
}
Error log:
09-19 12:59:11.367: E/Trace(2634): error opening trace file: No such file or directory (2)
The problem is with your code.
httppost = new HttpPost("localhost/android/index.php");
You can't access this link. You must give your IPAddress and port number along with this URL. and also your testing device must be in the same network to access this URL. It will be like this
httppost = new HttpPost("http://10.0.2.2:8080/android/index.php");
Please refer this Connect an Android Device To a Web Service on Local Host
public class MainActivity extends Activity implements OnClickListener {
Button login;
EditText username, password;
TextView status;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
TextView tv;
List<NameValuePair> nameValuePairs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
}
private void setup() {
// TODO Auto-generated method stub
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
status = (TextView) findViewById(R.id.tvstatus);
tv = (TextView) findViewById(R.id.editText1);
login.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.login :
new LoginOperation().execute();
break;
}
}
class LoginOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return login();
}
#Override
protected void onPostExecute(String result) {
tv.setText("" + result);
if (result.equalsIgnoreCase("User Found")) {
startActivity(new Intent(this, UserPage.class));
}
}
#Override
protected void onPreExecute() {
}
}
private String login() {
// TODO Auto-generated method stub
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("localhost/android/index.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username", username
.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password", password
.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
return response;
} catch (Exception ex) {
return "";
}
}
}
I'm trying to develop a simple app that gets data from web service and displays it
It throws exception exactly when he calls response.execute(client)
package com.example.webbasedapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
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 android.util.Log;
public class GETMethods {
public String getInternetData() throws Exception{
BufferedReader in=null;
String Data=null;
try{
HttpClient client=new DefaultHttpClient();
URI web=new URI("http://www.mybringback.com/");
HttpGet request = new HttpGet();
request.setURI(web);
HttpResponse reponse=client.execute(request);
Log.v("response code", reponse.getStatusLine()
.getStatusCode() + "");
InputStream inp=reponse.getEntity().getContent();
in=new BufferedReader(new InputStreamReader(inp));
StringBuffer buf=new StringBuffer();
String l="";
String nl=System.getProperty("line.separator");
while((l=in.readLine())!=null){
buf.append(l+nl);
}
in.close();
Data=buf.toString();
return Data;
}finally{
if(in!=null){
try{
in.close();
return Data;
}catch (Exception e){
Log.d("error",e.toString());
}
}
}
}
}
And this is my main activity
package com.example.webbasedapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class Home extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
TextView test = (TextView) findViewById(R.id.data);
GETMethods data = new GETMethods();
String d = null;
try {
d = data.getInternetData();
// test.setText(d);
} catch (Exception e) {
// TODO Auto-generated catch block
d = "bla";
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
// Log.d("testW",e.getMessage());
}
test.setText(d);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
You are attempting to access the network on the UI thread which is not allowed due to potential hangup issues. Look into AysncTask and implement GETMethods as one of them. It will look something like this:
public class GETMethods extends AsyncTask<String, Void, String>{
protected void doInBackground(String... params){
YourNetworkCode
}
}
I'm trying to get the data from the database for which I created a php file. It returns the name as the reply to the call. the website it Ensignweb
the program code goes like this.
The php file is like this
<?php
$connect = mysql_connect("localhost","databasename","password");
mysql_select_db("ews_app");
$query = mysql_query("select name from comment");
if(!empty($query)){
if(mysql_num_rows($query)>0){
WHILE($row=mysql_fetch_array($query)):
$comment = array();
$comment["name"] = $row['name'];
echo "$comment<br>";
echo json_encode($comment);
echo "<br>";
endwhile;
}
}
?>
The java code goes like this:
import java.io.IOException;
import java.io.Reader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://www.ensignweb.com/sandbox/app/comment11.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.data);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException,IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();//return 200 if execution is success
if(status==200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG);
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
But It is not displaying the json reply. I'm stucked in it from past few days.
Please help me out of it. I really need it.
sorry to be a pain, but I've been on this one too long and I am sure it's a easy one but I am tired and can't see it. All works fine but the 'String result' is empty
package com.example.me;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btnLoginButton;
TextView tmpError, tmpUsername, tmpPassword;
ArrayList<NameValuePair> postParameters;
String response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tmpError = (TextView) findViewById(R.id.lblMessage);
tmpUsername = (TextView) findViewById(R.id.txtUsername);
tmpPassword = (TextView) findViewById(R.id.txtPassword);
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
btnLoginButton = (Button) findViewById(R.id.btnLogin);
btnLoginButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg) {
try{
triggerClick();
}
catch (Exception e) {
tmpError.setText("[]" + e.toString());
}
}
});
}
private void triggerClick() {
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", tmpUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", tmpPassword.getText().toString()));
final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
#Override
protected String doInBackground(String... params) {
publishProgress(true);
try {
response = CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
return response;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
publishProgress(false);
result = result.replaceAll("\\s+","");
if(result.equals("1")) {
tmpError.setText("Correct");
}
else {
tmpError.setText("Sorry!!("+result+")");
}
}
}
new HttpTask().execute();
}
}
come back time and time again with an empty "result" string :-(
because in the doInBackground() you return empty string, you should do:
protected String doInBackground(String... params) {
publishProgress(true);
try {
return CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
The string result is empty because you're returning an empty string from doInBackground().
return "";
Please Declare String response; as a global variable.
protected String doInBackground(String... params)
{
publishProgress(true);
try
{
response=CustomHttpClient.executeHttpPost("http://some.url/thatiknoworks/check.php", postParameters);
return response;
}
catch (Exception e)
{
e.printStackTrace();
}
}