Insert data from android app into mySql database [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been following a youtube video which explain how to insert data from an android app to mySQL.
It doesn't work for me and I don't know what am I doing wrong. It just breaks as soon as I execute it. Not even loading the textViews and Buttons
This is my MainActivity:
package com.example.insertbbdd;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText eName, eAge, eMail;
Button bSumbit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
eName = (EditText) findViewById(R.id.editName);
eAge = (EditText) findViewById(R.id.editAge);
eMail = (EditText) findViewById(R.id.editMail);
bSumbit = (Button) findViewById(R.id.submitButton);
bSumbit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
InputStream is = null;
String name = "" + eName.getText().toString();
String age = "" + eAge.getText().toString();
String email = "" + eMail.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("age", age));
nameValuePairs.add(new BasicNameValuePair("email", email));
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://accessibility.es/prueba/script.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
String msg = "Data entered succesfully";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
catch(ClientProtocolException e){
Log.e("Client Protocol", "Log_tag");
e.printStackTrace();
}
catch(IOException e){
Log.e("Log tag", "IOException");
e.printStackTrace();
}
}
});
}
}
This is my main_activity.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/submitButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editName"
android:layout_alignParentBottom="true"
android:layout_marginBottom="130dp"
android:text="Button" />
<TextView
android:id="#+id/editMail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/submitButton"
android:layout_alignRight="#+id/editName"
android:layout_marginBottom="54dp"
android:layout_marginRight="17dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/editAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/editMail"
android:layout_alignLeft="#+id/editMail"
android:layout_marginBottom="43dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/editName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/editAge"
android:layout_alignParentLeft="true"
android:layout_marginBottom="35dp"
android:layout_marginLeft="90dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
And this is my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.insertbbdd"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

I'm guessing you are getting the ClassCastException because you are trying to call (EditText) on a TextView.
change this :
TextView eName, eAge, eMail;
eName = (TextView) findViewById(R.id.editName);
eAge = (TextView) findViewById(R.id.editAge);
eMail = (TextView) findViewById(R.id.editMail);
bSumbit = (Button) findViewById(R.id.submitButton);
or change your xml tag from TextView to EditText.
<EditText />
NB: what is pointed by others is also correct. if you click your submit button you will get
android.os.NetworkOnMainThreadException
so you need to use either Handler or AsyncTask

You need to carry out any network operations such as HttpPost (or indeed any other slow operation) in a separate thread from the main UI thread, and then use a callback to update the UI back on the main thread later.
See http://developer.android.com/guide/components/processes-and-threads.html and http://developer.android.com/reference/android/os/AsyncTask.html for the main documentation. There are also numerous guides on the web eg http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

try this..
try{
new Thread(new Runnable() {
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://accessibility.es/prueba/script.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
String msg = "Data entered succesfully";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
catch(ClientProtocolException e){
Log.e("Client Protocol", "Log_tag");
e.printStackTrace();
}
catch(IOException e){
Log.e("Log tag", "IOException");
e.printStackTrace();
}
}
}).start();

Related

connecting android app to webserver using post method

I'm trying to create a simple android app in which I'm trying to connect my app to a webserver where I have a database named akshaynsit1_pathaniswaad and in that database I have a table named table1. In this table I have 3 columns id(int auto increment primary key),name(varchar(30)),addr varchar(30).I'm creating a simple signup page where user will add his name and address and this name and address will get saved to my webserver through post method.
My MainActivity.java is as follows
package com.example.akshay007.sample;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
tv=(TextView)findViewById(R.id.textView2);
}
public void insert(View view){
String name = ed1.getText().toString();
String add = ed2.getText().toString();
insertToDatabase(name,add);
}
private void insertToDatabase(String name, String add){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramAddress = params[1];
try{
String name = paramUsername;
String address = paramAddress;
String link="http://http://pathaniswaad.com/android_akshay/post.php";
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
data += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(address, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
//return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "yo bro", Toast.LENGTH_LONG).show();
//TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
//textViewResult.setText("Inserted");
//tv.setText("ya brah..");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, add);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml is as follows
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:hint="name"
android:layout_centerHorizontal="true"
android:layout_marginTop="121dp" />
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:hint="address"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Signup"
android:id="#+id/button"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Merchant Signup"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Androidmanifest.xml is as follows
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.akshay007.sample" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
my post.php script is as follows
<?php
$con = mysqli_connect("65.50.265.181:336","jfjtyfyfhjfjdy","uitytityut67","akshaynsit1_pathaniswaad");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo"connection successful <br>";
}
$name = $_POST['name'];
$address = $_POST['address'];
$result = mysqli_query($con,"insert into table1 (name,addr) values ('$name','$address')");
if(mysqli_query($con,$sql)){
echo 'success';
}
else{
echo 'failure';
}
mysqli_close($con);
?>
Please help any kind of help would be appreciated!!!!!!!!!!
TWO things NEED to be fixed:
your post url link looks incorrect:
http://http://pathaniswaad.com/android_akshay/post.php
"http://" is used twice. change it to:
http://pathaniswaad.com/android_akshay/post.php
you have forgotten to append the params to url:
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
data += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(address, "UTF-8");
link += "?"+data; //add this line here
URL url = new URL(link);
Fix these 2 and try again. You should also test you PHP by using a fabricated url directly into your browser. that way it will make sure that there is no issue in the PHP itself.
good luck.
If you do not already have this in your manifest file, add it before the <application> section:
<uses-permission android:name="android.permission.INTERNET" />
Also, I have noticed that your link, in the code, is
http://http://pathaniswaad.com/android_akshay/post.php
Try changing it to
http://pathaniswaad.com/android_akshay/post.php
As the other user has also pointed out, you need the params appended. There is a better way to do this using loopj HttpAsyncClient:
Add to your gradle build:
compile 'com.loopj.android:android-async-http:1.4.9'
Here is a class I created to use this with GitHub Jobs, you can modify it for your uses:
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class AsyncRestClient {
private static final String BASE_URL = "https://jobs.github.com/positions";
private static final String JSON_RESPONSE_APPEND = ".json";
private static final AsyncHttpClient client = new AsyncHttpClient();
public static void getPositions(RequestParams params, AsyncHttpResponseHandler responseHandler) {
get(JSON_RESPONSE_APPEND, params, responseHandler);
}
private static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
And here is a code snippet where I use this class:
RequestParams params = jobRequested.getRequestParams();
AsyncRestClient.getPositions(params, getPositionsResponseHandler);
You would need to write your own response handler. If you want to see all the code, I have this project on GitHub (it is in active development), and you can see how I wrote the response handlers and callbacks for the responses:
https://github.com/JenniferVanderputten/GitHubJobs

Android, receive data from internet app does not work

I am completely new to android.
I am trying to build a basic app to get an idea on "android applications reading data from a server".
To get an idea about http connection on android i created this app watching a video tutorial, i have two java classes.
HttpExample.java class,
package com.raveen.testingthree;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.TextView;
public class HttpExample extends Activity {
TextView httpStuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
httpStuff = (TextView) findViewById(R.id.tvHttp);
GetMethodHttp test = new GetMethodHttp();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and getmethodhttp.java class,
package com.raveen.testingthree;
import java.io.BufferedReader;
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;
public class GetMethodHttp {
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 responce = client.execute(request);
in = new BufferedReader(new InputStreamReader(responce.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String newLine = System.getProperty("line.separator");
while((line = in.readLine()) != null){
sb.append(line + newLine);
}
in.close();
data = sb.toString();
return data;
} finally {
if (in != null){
try{
in.close();
return data;
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}
this is my AndroidManifest,
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HttpExample"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and my layout xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/tvHttp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading Data"
android:textSize="20dp"
/>
</ScrollView>
</LinearLayout>
now when i run this on emulator or my android phone NOTHING IS DISPLAYED.. Just a blank white layout is visible.. what am i doing wrong here?
(i am using eclipse to program)
First of all you should not change the policy to force network calls on main thread instead use Async task.
If you want to read html contents then use jsoup which allows to parse html.
If you want to read data from webservice then try VOLLEY Library.This will save your time,works more efficiently and traceable.

Send Data to Wampserver Android

I made a project which must generate a page on entering message, but it is not working for a reason. I am posting the code below.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/hello_world" />
<EditText
android:id="#+id/edit1"
android:layout_margin="20dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="Write a message"
>
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter"
android:onClick="send"
/>
</LinearLayout>
MainActivity.java
package com.example.postapp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText edit1;
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit1 = (EditText) findViewById(R.id.edit1);
button1 = (Button) findViewById(R.id.button1);
}
#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;
}
public void send(View v)
{
String msg = edit1.getText().toString();
if(msg.length()>0)
{ //Toast.makeText(getBaseContext(), "enter length", Toast.LENGTH_SHORT).show();
HttpClient httpc = new DefaultHttpClient();
HttpPost httpost = new HttpPost("http://localhost/demo/server_scripr.php");
//Toast.makeText(getBaseContext(), "enter length0", Toast.LENGTH_SHORT).show();
try
{
List<BasicNameValuePair> vp = new ArrayList<BasicNameValuePair>();
//vp.add(new BasicNameValuePair("id","01"));
vp.add(new BasicNameValuePair("message",msg));
httpost.setEntity(new UrlEncodedFormEntity(vp));
httpc.execute(httpost);
edit1.setText("");
Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Please enter the field", Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.postapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.postapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Thanks, help me in finding the solution
The error is most likely within this line of your code:
HttpPost httpost = new HttpPost("http://localhost/demo/server_scripr.php");
Make sure it isn't supposed to be:
/server_script.php

my app is crashing when i click on the button

When I click my send button on my app the app crashes with:
06-30 13:57:46.487: E/AndroidRuntime(12201): FATAL EXCEPTION: main
06-30 13:57:46.487: E/AndroidRuntime(12201): java.lang.IllegalStateException:
Could not find a method send(View) in the activity class com.yoursite.helloworld.MainActivity
for onClick handler on view class android.widget.Button with id 'sendButton'
my MainActivity.java:
package com.yoursite.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
}
my HelloWorldActivity.java:
package com.yoursite.helloworld;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class HelloWorldActivity extends Activity {
Button sendButton;
EditText msgTextField;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// load the layout
setContentView(R.layout.activity_main);
// make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
// make send button object
sendButton = (Button) findViewById(R.id.sendButton);
}
// this is the function that gets called when you click the button
public void send(View v)
{
// get the message from the message text box
String msg = msgTextField.getText().toString();
// make sure the fields are not empty
if (msg.length()>0)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mysite.com/test.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "12345"));
nameValuePairs.add(new BasicNameValuePair("name", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
}
my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="#+id/msgTextField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:text="Send"
android:id="#+id/sendButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="send"
/>
</LinearLayout>
and AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yoursite.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.yoursite.helloworld.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Im trying to follow this tutorial http://webtutsdepot.com/2011/11/15/android-tutorial-how-to-post-data-from-an-android-app-to-a-website/ and have tried everything with no success, need some beginner help please!
Your send() method is in HelloWorldActivity, while your layout is inflated in MainActivity.
Either move your send() method into MainActivity, or inflate your layout in your other Activity.

Posting to a URL with Android?

OK, been stuck on this one for quite a while now. Not an expert with Java but been trying to create an app to simply post information to a URL. Don't know where my code is going wrong? Please can you have a look and advise? Sorry to upload loads of code don't really know how to explain it as I don't know where I am going wrong. No errors in the console, emulator just fails to load app fully?
import java.io.IOException;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class test {
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "name"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="72dp"
android:layout_marginTop="36dp"
android:ems="10"
android:inputType="text"
android:text="#string/Enter_name" >
<Button
android:id="#+id/Submit_Transaction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="40dp"
android:layout_toRightOf="#+id/textView1"
android:onClick="postData()"
android:text="#string/Submit_Tran_Button" />
<activity
android:name="com.testing.myappname.PostData"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
LogCat starts with FATAL EXCEPTION MAIN error then...
01-21 21:52:44.459: E/AndroidRuntime(1155): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.test.testing/com.testing.testing.PostData}: java.lang.ClassNotFoundException: Didn't find class "com.testing.testingvt.PostData" on path: /data/app/com.testing.testingvt-1.apk
Ok. The problem here is that you should have a valid Activity class to display your UI. Just read about Activities on this link.

Categories

Resources