I already posted this issue but had edited it so many times I thought I would just post again with all the code and the eclipse package download.
I am not getting any errors/problems in eclipse after I changed class extends Activity to class extends ListActivity.
If anyone see my issues that may be forcing the app to close please let me know. THANKS!
ECLIPSE PROJECT DOWNLOAD
patriotsar.java
package com.patriotsar;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.patriotsar.XMLfunctions;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class patriosar extends ListActivity {
private Button goButton;
private Button quoteButton;
String url = "http://www.patriotsar.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goButton = (Button)findViewById(R.id.goButton);
quoteButton = (Button)findViewById(R.id.quoteButton);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
i.setData(u);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
quoteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(patriosar.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", "Naam:" + XMLfunctions.getValue(e, "name"));
map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
mylist.add(map);
}
//
ListAdapter adapter = new SimpleAdapter(patriosar.this, mylist , R.layout.main,
new String[] { "name", "Score" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(patriosar.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show();
}
});
}
});
}
}
XMLfunctions.java
package com.patriotsar;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XMLfunctions {
public final static Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://p-xr.com/xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}
ListPlaceholder.xml:
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView
android:id="#id/android:empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="No data"/>
</LinearLayout>
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bgimage2">
>
<Button
android:id="#+id/quoteButton"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="#string/start"
android:layout_x="80px"
android:layout_y="21px"
>
</Button>
<Button
android:id="#+id/goButton"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="#string/subscribe"
android:layout_x="80px"
android:layout_y="74px"
>
</Button>
<TextView
android:id="#+id/textview"
android:layout_width="300px"
android:layout_height="fill_parent"
android:text="#string/intro"
android:layout_y="300px"
android:layout_x="20px"
android:textColor="#ffffff"
/>
<TextView
android:id="#+id/item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:padding="2dp"
android:textSize="20dp" />
<TextView
android:id="#+id/item_subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="13dp" />
</AbsoluteLayout>
Android Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.patriotsar"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="3" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".patriosar"
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>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
You're extending ListActivity. The layout that you use in setContentView() needs to have a ListView with the id #android:id/list.
Edit
Also, AbsoluteLayouts are deprecated. You should not use them. However, this isn't causing your app to force close.
Related
I am new to android studio and I tried to get html content of a webpage using AsyncTask class(deprecated API).I have attached my AndroidManifest.xml file. I have added the neccessary permisions to access internet,still i am getting the error "E/Zygote : no v2" and my app crashes. Please explain what does this error mean and how to eliminate the error.I launched the app in a phone with Android 6.0.1
public class MainActivity extends AppCompatActivity {
public static class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... urls) {
String result ="";
URL url;
HttpsURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection =(HttpsURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data!=-1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
But the LogCat came up with this error
[08-11 11:46:36.426 27036-27036/? E/Zygote: no v2
08-11 11:46:36.426 27036-27036/? W/SELinux: Function: selinux_compare_spd_ram, index[1], priority [2], priority version is VE=SEPF_SECMOBILE_6.0.1_0035
08-11 11:46:36.436 27036-27036/? W/SELinux: SELinux: seapp_context_lookup: seinfo=default, level=s0:c512,c768, pkgname=com.example.guessthecelebrity
08-11 11:46:36.436 27036-27036/? I/art: Late-enabling -Xcheck:jni
08-11 11:46:36.827 27036-27036/com.example.guessthecelebrity D/ResourcesManager: For user 0 new overlays fetched Null
08-11 11:46:36.847 27036-27036/com.example.guessthecelebrity W/System: ClassLoader referenced unknown path: /data/app/com.example.guessthecelebrity-2/lib/arm
08-11 11:46:36.907 27036-27036/com.example.guessthecelebrity D/ResourcesManager: For user 0 new overlays fetched Null
08-11 11:46:36.927 27036-27036/com.example.guessthecelebrity W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guessthecelebrity">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permissioandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:largeHeap="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
I guess you are not good at using AsyncTask. You are not executing the AsyncTask anywhere. How ever, a better clean approach will be as follows,
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/url_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Input a web page url to get." />
<Button
android:id="#+id/url_request_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Request Page"
android:onClick="downloadSiteData"/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/url_response"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
MainActivity with AsyncTask:
package com.example.downloadsite;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText urlRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
urlRequest = findViewById(R.id.url_request);
}
public void downloadSiteData(View view) {
String url = urlRequest.getText().toString();
if ( url.equals("")) {
Toast.makeText(MainActivity.this, "URL can't be empty", Toast.LENGTH_SHORT).show();
}
else {
new DownloadTask().execute(url);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "Downloading site data", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... urls) {
String value = urls[0];
String response = null;
URL url = null;
HttpURLConnection urlConnection = null;
InputStream in = null;
try {
url = new URL(value);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
response = readStream(in);
} catch (Exception e) { e.printStackTrace(); }
finally {
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String nextLine = "";
String newLine = "";
while ((newLine = reader.readLine()) != null) {
sb.append(nextLine + newLine);
}
} catch (IOException e) { e.printStackTrace(); }
return sb.toString();
}
#Override
protected void onPostExecute(String responseString) {
super.onPostExecute(responseString);
TextView tv = findViewById(R.id.url_response);
tv.setText(responseString);
}
}
}
To debug, I tried to migrate to a blank activity still it shows the same error. Can't understand why!
So i have that error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: thingtranslator2.jalle.com.thingtranslator2, PID: 14918
java.lang.IllegalStateException: Could not execute method for android:onClick
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24704)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24704)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/thingtranslator2.jalle.com.thingtranslator2/cache/tempImage exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1958)
at android.net.Uri.checkFileUriExposed(Uri.java:2357)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:941)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9735)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9741)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9720)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1618)
at android.app.Activity.startActivityForResult(Activity.java:4482)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4440)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at thingtranslator2.jalle.com.thingtranslator2.MainActivity.getImage(MainActivity.java:157)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24704)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
And this is my MainActivity code :
package thingtranslator2.jalle.com.thingtranslator2;
import android.app.ProgressDialog;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.pixplicity.easyprefs.library.Prefs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import thingtranslator2.jalle.com.thingtranslator2.Rest.ApiInterface;
import thingtranslator2.jalle.com.thingtranslator2.Rest.Translation;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public
#BindView(R.id.txtTranslation)
TextView txtTranslation;
public
#BindView(R.id.spinner)
Spinner spinner;
public
#BindView(R.id.imgPhoto)
ImageButton imgPhoto;
public
#BindView(R.id.imgSpeaker)
ImageButton btnSpeaker;
public Boolean speakerOn, firstRun;
public TextToSpeech tts;
public List<String> languages = new ArrayList<String>();
public ArrayList<Language> languageList = new ArrayList<Language>();
public ArrayAdapter<Language> spinnerArrayAdapter;
public Language selectedLanguage;
public static final int PICK_IMAGE_ID = 234; // the number doesn't matter
thingtranslator2.jalle.com.thingtranslator2.Tools.MarshMallowPermission marshMallowPermission = new thingtranslator2.jalle.com.thingtranslator2.Tools.MarshMallowPermission(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
ButterKnife.bind(this);
btnSpeaker = (ImageButton)findViewById(R.id.imgSpeaker);
imgPhoto = (ImageButton)findViewById(R.id.imgPhoto);
spinner = (Spinner)findViewById(R.id.spinner);
txtTranslation = (TextView)findViewById(R.id.txtTranslation);
//init our Shared preferences helper
new Prefs.Builder()
.setContext(this)
.setMode(ContextWrapper.MODE_PRIVATE)
.setPrefsName(getPackageName())
.setUseDefaultSharedPreference(true)
.build();
// Prefs.clear();
firstRun = Prefs.getBoolean("firstRun", true);
spinner.setOnItemSelectedListener(this);
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
fillSpinner();
}
}
});
if (firstRun) {
Prefs.putBoolean("firstRun", false);
Prefs.putBoolean("speakerOn", true);
Prefs.putString("langCode", "bs");
}
setSpeaker();
}
private void setSpeaker() {
int id = Prefs.getBoolean("speakerOn", false) ? R.drawable.ic_volume : R.drawable.ic_volume_off;
btnSpeaker.setImageBitmap(BitmapFactory.decodeResource(getResources(), id));
}
public void ToogleSpeaker(View v) {
Prefs.putBoolean("speakerOn", !Prefs.getBoolean("speakerOn", false));
setSpeaker();
Toast.makeText(getApplicationContext(), "Speech " + (Prefs.getBoolean("speakerOn", true) ? "On" : "Off"), Toast.LENGTH_SHORT);
}
private void fillSpinner() {
Iterator itr = tts.getAvailableLanguages().iterator();
while (itr.hasNext()) {
Locale item = (Locale) itr.next();
languageList.add(new Language(item.getDisplayName(), item.getLanguage()));
}
//Sort that array
Collections.sort(languageList, new Comparator<Language>() {
#Override
public int compare(Language o1, Language o2) {
return o1.getlangCode().compareTo(o2.getlangCode());
}
});
spinnerArrayAdapter = new ArrayAdapter<Language>(this, R.layout.spinner_item, languageList);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
String def = Prefs.getString("langCode", "bs");
for (Language lang : languageList) {
if (lang.getlangCode().equals(def)) {
spinner.setSelection(languageList.indexOf(lang));
}
}
}
//Get image from Gallery or Camera
public void getImage(View v) {
if (!marshMallowPermission.checkPermissionForCamera()) {
marshMallowPermission.requestPermissionForCamera();
} else {
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
} else {
Intent chooseImageIntent = thingtranslator2.jalle.com.thingtranslator2.Tools.ImagePicker.getPickImageIntent(getApplicationContext());
startActivityForResult(chooseImageIntent, PICK_IMAGE_ID);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) return;
switch (requestCode) {
case PICK_IMAGE_ID:
Bitmap bitmap = thingtranslator2.jalle.com.thingtranslator2.Tools.ImagePicker.getImageFromResult(this, resultCode, data);
imgPhoto.setImageBitmap(null);
imgPhoto.setBackground(null);
imgPhoto.setImageBitmap(bitmap);
imgPhoto.invalidate();
imgPhoto.postInvalidate();
File file = null;
try {
file = savebitmap(bitmap, "pic.jpeg");
} catch (IOException e) {
e.printStackTrace();
}
uploadImage(file);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
private void uploadImage(File file) {
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody langCode1 = RequestBody.create(MediaType.parse("text/plain"), selectedLanguage.langCode);
final ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Processing image...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
ApiInterface mApiService = ApiInterface.retrofit.create(ApiInterface.class);
Call<Translation> mService = mApiService.upload(body, langCode1);
mService.enqueue(new Callback<Translation>() {
#Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
progress.hide();
Translation result = response.body();
txtTranslation.setText(result.Translation);
txtTranslation.invalidate();
if (Prefs.getBoolean("speakerOn", true)) {
tts.speak(result.Translation, TextToSpeech.QUEUE_FLUSH, null);
}
}
#Override
public void onFailure(Call<Translation> call, Throwable t) {
call.cancel();
progress.hide();
Toast.makeText(getApplicationContext(), "Error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public static File savebitmap(Bitmap bmp, String fName) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + fName);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedLanguage = (Language) spinner.getSelectedItem();
// langCode = languages.get(position);
tts.setLanguage(Locale.forLanguageTag(selectedLanguage.langCode));
Prefs.putString("langCode", selectedLanguage.langCode);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBlack"
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
tools:context="thingtranslator2.jalle.com.thingtranslator2.MainActivity">
<LinearLayout
android:id="#+id/layout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:weightSum="1">
<Spinner
android:id="#+id/spinner"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_marginBottom="16dp"
android:layout_weight="0.91"
android:gravity="bottom|end" />
<ImageButton
android:id="#+id/imgSpeaker"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="end"
android:layout_weight=".10"
android:background="#android:color/transparent"
android:onClick="ToogleSpeaker"
android:scaleType="fitCenter"
app:srcCompat="#drawable/ic_volume"
android:contentDescription="#string/todo" />
</LinearLayout>
<TextView
android:id="#+id/txtTranslation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/layout1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:gravity="center_horizontal"
android:onClick="getImage"
android:text="#string/select_image_from_n_gallery_or_take_new_photo"
android:textColor="#android:color/white"
android:textSize="26sp"
tools:text="message" />
<ImageButton
android:id="#+id/imgPhoto"
android:layout_width="fill_parent"
android:layout_height="400dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_below="#id/txtTranslation"
android:background="#drawable/takephoto"
android:onClick="getImage" />
</RelativeLayout>
AndroidMnifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thingtranslator2.jalle.com.thingtranslator2">
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
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
I want to write data into a SD card but I am getting the following error: Failed open failed: EACCES (Permission denied).
The Android version I am working on is jelly bean(4.3).
I have also given permission in manifest file.
Here is my code:
package com.example.androidsdcard;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
// GUI controls
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
File sample=null;
String SDCard_Path="/mnt/extsd";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
File storageDir = new File(SDCard_Path);
String sample1 = Environment.getExternalStorageDirectory().getPath();
Toast.makeText(MainActivity.this,sample1, Toast.LENGTH_LONG).show();
if(sample == null)
{
Toast.makeText(MainActivity.this,"Sample == null executed", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(MainActivity.this,"Sample == null skipped", Toast.LENGTH_LONG).show();
if(storageDir.isDirectory())
{
String[] dirList = storageDir.list();
if(dirList==null)
{
Toast.makeText(getBaseContext(),"Failed to detect SD card",Toast.LENGTH_SHORT).show();
return;
}
else
Toast.makeText(getBaseContext(),"SD Card Detected",Toast.LENGTH_SHORT).show();
}
try {
File myFile = new File("/mnt/extsd/MedeQuip.txt");
/* if(myFile.createNewFile()==false)
{
Toast.makeText(getBaseContext(),"Unable to create File'",Toast.LENGTH_SHORT).show();
return;
}
else
Toast.makeText(getBaseContext(),"File Created'",Toast.LENGTH_SHORT).show();
*/ FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD mysdfile.txt'",Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnWriteSDFile
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// write on SD card file data in the text box
try
{
File myFile = new File(SDCard_Path+"/MedeQuip.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),"Done reading SD 'MedeQuip.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
txtData.setText("");
}
}); // btnClearScreen
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
finish();
}
}); // btnClose
}// onCreate
}// AndSDcard
Here is my xml:
<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">
<EditText
android:id="#+id/txtData"
android:layout_width="fill_parent"
android:layout_height="180px"
android:textSize="18sp" />
<Button
android:id="#+id/btnWriteSDFile"
android:layout_width="143px"
android:layout_height="44px"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtData"
android:layout_marginTop="60dp"
android:text="1. Write SD File" />
<Button
android:id="#+id/btnClearScreen"
android:layout_width="141px"
android:layout_height="42px"
android:layout_alignBaseline="#+id/btnWriteSDFile"
android:layout_alignBottom="#+id/btnWriteSDFile"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/btnWriteSDFile"
android:text="2. Clear Screen" />
<Button
android:id="#+id/btnReadSDFile"
android:layout_width="140px"
android:layout_height="42px"
android:layout_alignTop="#+id/btnWriteSDFile"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#+id/btnClearScreen"
android:text="3. Read SD File" />
<Button
android:id="#+id/btnClose"
android:layout_width="141px"
android:layout_height="43px"
android:layout_alignTop="#+id/btnClearScreen"
android:layout_marginLeft="61dp"
android:layout_toRightOf="#+id/btnReadSDFile"
android:text="4. Close" />
</RelativeLayout>
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidsdcard"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>
You cannot assume external storage will always be at "/mnt/extsd". Very rarely will this be the case as it is up to the OEM where the mount points are. Use the standard APIs from the Context object to get the correct locations of interest: Context.getExternalFilesDir() and Context.getExternalFilesDirs().
the problem is with jelly bean
this work for me
String path = null;
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
path = getActivity().getCacheDir() + File.separator + "name";
} else{
path = Environment.getExternalStorageDirectory() + File.separator + "name";
}
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();