I am creating an app to check whether the given address of a server is valid or not. It sends request to a server when Connect button is pressed. If request succeed it is valid if not invalid ...
But I am having an error when I run a thread. I cant run it on Computer caz having issues enabling ADV but here is my code.
Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Server Address"
app:layout_constraintBottom_toTopOf="#+id/addressInput"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.869" />
<EditText
android:id="#+id/addressInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:hint="Enter your server address"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/addressBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connect"
android:onClick="onAddressButtonClick"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/addressInput"
app:layout_constraintVertical_bias="0.065" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity
package com.naveed.youtubestream;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private Button addressBtn;
private EditText addressInput;
private String serverAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressBtn = findViewById(R.id.addressBtn);
addressInput = findViewById(R.id.addressInput);
}
private boolean checkAddress(String address){
try {
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
return true;
}
} catch (IOException e) { }
return false;
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
try{
if(checkAddress(serverAddress)){
//TODO --> Set new Layout
Toast.makeText(getApplicationContext(), "Server address was valid.", Toast.LENGTH_LONG).show();
}
else {
addressInput.setText("");
Toast.makeText(getApplicationContext(), "Invalid server address.", Toast.LENGTH_LONG).show();
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
};
public void onAddressButtonClick(View view) {
try{
serverAddress = addressInput.getText().toString();
Thread thread = new Thread(runnable);
thread.start();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.naveed.youtubestream">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="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>
Related
This is my entire code from an android project
Translator.java:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Translator extends AppCompatActivity {
EditText input;
TextView translated;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void translate (View view) throws IOException {
input = (EditText) findViewById(R.id.input);
String text = input.getText().toString();
translated = (TextView) findViewById(R.id.translatedText);
String langFrom = "en";
String langTo = "hi";
// INSERT YOU URL HERE
String urlStr = "https://script.google.com/macros/s/AKfycbxt1kjnGx5twzn8lGZopvHkivUCL-B8su8PLXsSRlByiAdRKgA/exec" +
"?q=" + URLEncoder.encode(text, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String output = response.toString();
translated.setText(output);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FAF3BD"
tools:context=".Translator">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tagLine"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.023" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout"
android:layout_width="300dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.144"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.069">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="#string/input"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/translateButton"
android:layout_width="175dp"
android:layout_height="67dp"
android:background="#FF9800"
android:onClick="translate"
android:text="#string/translateButton"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.46" />
enter code here
<com.google.android.material.textfield.TextInputLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/translateButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.144"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayout"
app:layout_constraintVertical_bias="0.558">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/target_language"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:id="#+id/translatedText"
android:layout_width="305dp"
android:layout_height="215dp"
android:background="#FDDB73"
android:scrollY="500dp"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideOverlay"
android:scrollHorizontally="false"
android:shadowColor="#FFFFFF"
android:text="#string/translated"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.494"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/translateButton"
app:layout_constraintVertical_bias="0.751" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/translated_text"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/translatedText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/translateButton"
app:layout_constraintVertical_bias="0.731" />
<View
android:id="#+id/divider2"
android:layout_width="350dp"
android:layout_height="2dp"
android:layout_marginTop="83dp"
android:layout_marginBottom="12dp"
android:background="?android:attr/listDivider"
app:layout_constraintBottom_toTopOf="#+id/textView3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/translateButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dhimanujjwal.anuvaad">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Translator">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat:
Process: com.dhimanujjwal.anuvaad, PID: 14480
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6412)
at android.view.View$PerformClick.run(View.java:25341)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6977)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6412)
at android.view.View$PerformClick.run(View.java:25341)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6977)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:299)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:237)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(Unknown Source:0)
at com.dhimanujjwal.anuvaad.Translator.translate(Translator.java:45)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6412)
at android.view.View$PerformClick.run(View.java:25341)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6977)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910)
You are getting Caused by: android.os.NetworkOnMainThreadException. I think it says everything. To execute operations like this You have to do it on another thread. You can use JobIntentService.
In Your manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.teststackjava">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="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>
<service
android:name=".ExampleJobIntentService"
android:permission="android.permission.BIND_JOB_SERVICE" />
</application>
</manifest>
MainActivity:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
public class MainActivity extends AppCompatActivity
{
EditText input;
TextView translated;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void translate(View view)
{
input = (EditText) findViewById(R.id.input);
String text = input.getText().toString();
translated = (TextView) findViewById(R.id.translatedText);
// setting observer to translated text
ExampleJobIntentService.translatedText.observe(this,
new Observer<String>()
{
#Override
public void onChanged(String s)
{
translated.setText(s); // change text
}
}
);
Intent serviceIntent = new Intent(this,
ExampleJobIntentService.class
);
serviceIntent.putExtra("inputExtra", text);
ExampleJobIntentService.enqueueWork(this, serviceIntent);
}
}
Then create class which extends JobIntentService:
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.lifecycle.MutableLiveData;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class ExampleJobIntentService extends JobIntentService
{
private static final String TAG = "ExampleJobIntentService";
// This is data type which can be observed by another class
public static MutableLiveData<String> translatedText = new MutableLiveData<>(); // I made it public, better to use private and getter
static void enqueueWork(Context context, Intent work)
{
enqueueWork(context, ExampleJobIntentService.class, 123, work);
}
#Override
public void onCreate()
{
super.onCreate();
Log.d(TAG, "onCreate");
}
#Override
protected void onHandleWork(#NonNull Intent intent)
{
Log.d(TAG, "onHandleWork");
String input = intent.getStringExtra("inputExtra");
String langFrom = "en";
String langTo = "hi";
// INSERT YOU URL HERE
try
{
String urlStr = "https://script.google.com/macros/s/AKfycbxt1kjnGx5twzn8lGZopvHkivUCL-B8su8PLXsSRlByiAdRKgA/exec" +
"?q=" + URLEncoder.encode(input, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
String output = response.toString();
Log.i(TAG, "onHandleWork: " + output);
translatedText.postValue(output);//here I am updating data
}
catch (IOException e)
{
Log.i(TAG, "onHandleWork: ERROR");
}
}
#Override
public void onDestroy()
{
Log.d(TAG, "onDestroy");
super.onDestroy();
}
#Override
public boolean onStopCurrentWork()
{
Log.d(TAG, "onStopCurrentWork");
return super.onStopCurrentWork();
}
}
activity_main.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">
<EditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="input"
android:textSize="24sp" />
<Button
android:id="#+id/translateButton"
android:layout_width="175dp"
android:layout_height="67dp"
android:background="#FF9800"
android:onClick="translate"
android:text="translateButton"
android:textSize="30sp" />
<TextView
android:id="#+id/translatedText"
android:layout_width="305dp"
android:layout_height="215dp"
android:background="#FDDB73"
android:scrollY="500dp"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideOverlay"
android:scrollHorizontally="false"
android:shadowColor="#FFFFFF"
android:text="translated"
android:textSize="24sp" />
</LinearLayout>
I have tested this and it seems to work when I tried to translate School I got स्कूल.
I think you forgot to account for the Button in the Java file, you need to create and link the Button and then setOnClickListener() for it , to tell what happens when the Button Clicks.
Your method transform should must match signature of View.OnClickListener.
You need delete throws IOException it, and handle exception inside method with try/catch block
If you run your app in device with version Android 9 (API level 28) or later, cleartext support is disabled by default. Then your AndroidManifest.xml file should add the line:
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 4 years ago.
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.adufordjour.external">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="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>
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.adufordjour.external.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:layout_marginTop="61dp"
android:text="NAME"
android:id="#+id/textView"
/>
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="32dp"
android:layout_marginTop="44dp"
android:layout_toEndOf="#+id/textView"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/editText"
android:layout_centerVertical="true"
android:text="Save"
android:onClick="sAVE"/>
</RelativeLayout>
Android code
This is the code for storing data on a public external device:
package com.example.adufordjour.external;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
EditText editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = findViewById(R.id.editText);
}
This is the method for saving to the public external device
public void sAVE(View view){
String st1 = editText1.getText().toString();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "myFile");
FileOutputStream fileOutputStream=null;
try {
if (isExternalStorageWritable()==true){
fileOutputStream =new FileOutputStream(file);
fileOutputStream.write(st1.getBytes());}
else {
Toast.makeText(this, "not saved", Toast.LENGTH_SHORT).show();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fileOutputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "file save at" + " " + "myFile", Toast.LENGTH_SHORT).show();
}
public boolean isExternalStorageWritable(){
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
else {
return false;
}
}
}
Why do you use android:maxSdkVersion="18" in uses-permission? I think it's not needed there.
Try to add READ_EXTERNAL_STORAGE permission and check if it worked. If not, paste stack trace of your crash.
I'm trying to implement a login Activity. In login Activity, I have to enter Mobile number and password and then click the Login button.
Here is my activity_login.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background2"
tools:context="com.myayubo.LoginActivity"
android:fillViewport="false">
<RelativeLayout
android:id="#+id/RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="25dp">
<LinearLayout
android:id="#+id/LinearLayouttxtayubo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/textAyubo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ayubo"
android:layout_gravity="center"
android:typeface="normal"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:textSize="35dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayouttxtexplorer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/LinearLayouttxtayubo"
android:orientation="vertical">
<TextView
android:id="#+id/textExplore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explore places nearby you"
android:layout_centerHorizontal="true"
android:typeface="serif"
android:layout_gravity="center"
android:textColor="#FFFFFF"
android:textSize="12dp"/>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/LinearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginTop="224dp"
android:layout_below="#+id/RelativeLayout1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<EditText
android:id="#+id/mobileNo"
android:layout_width="250dp"
android:layout_height="30dp"
android:hint="Mobile Number"
android:textColorHint="#FFFFFF"
android:gravity="center"
android:inputType="phone"
android:layout_gravity="center"
android:background="#drawable/shape"
android:layout_marginTop="10dp"
android:textSize="15dp"
>
<requestFocus />
</EditText>
<EditText
android:id="#+id/password"
android:layout_width="250dp"
android:layout_height="30dp"
android:hint="Password"
android:textColorHint="#FFFFFF"
android:inputType="textPassword"
android:layout_gravity="center"
android:background="#drawable/shape"
android:layout_marginTop="10dp"
android:gravity="center"
android:textSize="15dp"/>
<Button
android:id="#+id/loginBtn"
android:text="Login"
android:layout_width="260dp"
android:layout_height="38dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:alpha="0.5" />
<Button
android:id="#+id/fbbtn"
android:text="Connect with Facebook"
android:layout_width="250dp"
android:layout_height="26dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:background="#ADD8E6"
android:alpha="0.5"
/>
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/fbbtn"
android:layout_marginTop="20dp"
android:text="or Sign Up"
android:layout_gravity="center"/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
And Here is my LoginActivity.java
package com.myayubo;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.myayubo.services.MessageHandler;
import com.myayubo.services.ServiceHandler;
import org.json.JSONObject;
public class LoginActivity extends ActionBarActivity implements View.OnClickListener {
public final static String URL = "";
public static String Uid;
private EditText contact;
private EditText password;
private Button login;
private Button fbBtn;
private TextView signUp;
private boolean errorStatus;
private ServiceHandler sh = new ServiceHandler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
contact = (EditText) findViewById(R.id.mobileNo);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.loginBtn);
fbBtn = (Button) findViewById(R.id.fbbtn);
signUp = (TextView) findViewById(R.id.signUp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!ServiceHandler.isOnline(getApplicationContext())){
MessageHandler.showMessage("No network connection",
getApplicationContext());
}
new Thread(new Runnable() {
public void run() {
Looper.prepare();
String mobile = contact.getText().toString();
String passwrd = password.getText().toString();
if (mobile.length() == 0){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Contact Number",
getApplicationContext());
errorStatus = true;
}
});
;
}
if (passwrd.length() == 0){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Password",
getApplicationContext());
errorStatus = true;
}
});
;
}
String jsonStr = null;
if (!errorStatus) {
if (!ServiceHandler.isOnline(getApplicationContext())) {
MessageHandler.showMessage("No network connection",
getApplicationContext());
} else {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// notify user you are online
try{
runOnUiThread(new Runnable() {
public void run() {
}
});
;
jsonStr = sh.makeServiceCall(URL + "/" + mobile + "/"
+ passwrd, ServiceHandler.GET);
System.out.println(URL + "/" + mobile + "/"
+ passwrd);
}
catch (Exception e){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage("No network connection",
getApplicationContext());
}
});
;
}
}
if (jsonStr != null) {
String status = "";
String msg = "";
try {
JSONObject jsonObj = new JSONObject(jsonStr);
runOnUiThread(new Runnable() {
public void run() {
}
});
;
if (jsonObj != null
&& jsonObj.has("status")) {
status = jsonObj.getString("status");
msg = jsonObj.getString("message");
if(jsonObj.has("uid"))
Uid = jsonObj.getString("uid");
System.out.println(jsonObj);
if (status.equals("OK")) {
Intent myIntent = new Intent(
getBaseContext(),
ExtractMenu.class);
startActivityForResult(myIntent, 0);
} else if (status.equals("ERROR")) {
final String errorMsg = msg;
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
errorMsg,
getApplicationContext());
}
});
;
} else {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
"Oops..! something wrong with the service. Please try again Later.",
getApplicationContext());
}
});
;
}
}
} catch (Exception e) {
System.out
.println("Creation of json object failed");
}
}
}
}
}).start();
}
});
signUp.setOnClickListener(this);
}
#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_login, 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);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(this, sign_up.class);
startActivity(intent);
}
}
Looks like something is wrong here. Because, when I'm trying to run this code, my app crashes. It shows the following error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myayubo/com.myayubo.LoginActivity}: java.lang.NullPointerException
But, without intent for signUp button it works.
Here is my logcat.
11-05 10:36:58.359 27532-27532/com.myayubo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.myayubo, PID: 27532
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myayubo/com.myayubo.LoginActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.myayubo.LoginActivity.onCreate(LoginActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Please some1 tell me what to do with this error.
Thaks in advance.
-Edit -
Here is the Manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myayubo"
android:versionCode="1"
android:versionName="1.0" >
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--
To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user. This disconnect
option is required to comply with the Google+ Sign-In developer policies
-->
<uses-permission android:name="android.permission.USE_CREDENTIALS" /> <!-- To retrieve the account name (email) as part of sign-in: -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login"
android:windowSoftInputMode="adjustResize|stateHidden" >
</activity>
<activity
android:name=".Splash"
android:label="Ayubo" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ExtractMenu"
android:label="#string/title_activity_extract_menu" >
</activity>
<activity
android:name=".sign_up"
android:label="#string/title_activity_sign_up" >
</activity>
</application>
</manifest>
you are getting NPE because you are trying to add view which is not in your xml file
signUp = (TextView) findViewById(R.id.signUp);
there is no text view in your xml with this id. check it out if you remove this your code will run perfectly
NullPointerException Because there isn't any TextView with id signUp in activity_login.xml layout.
In your onCreate Method
signUp = (TextView) findViewById(R.id.signUp);
But as your activity_login.xml does not contain TextView with id signUp it return null,
And again you try to set listener on that TextView which is null so NullPointerException
signUp.setOnClickListener(this);
Looks like you fogot to set id here,
<TextView
android:id="#+id/text2" //android:id="#+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/fbbtn"
android:layout_marginTop="20dp"
android:text="or Sign Up"
android:layout_gravity="center"/>
This is my AndroidManifest.xml
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:name="MBCRADIO" android:label="MBCRADIO">
<activity
android:name=".ListenMBC"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
AND ListenMBC.java file here ...
package org.apache.android.media;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.widget.Button;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.content.Intent;
public class ListenMBC extends Activity {
private static final String TAG = "radioListen";
private Button buttonPlaymbc1;
private Button buttonPlaymbc2;
private Button buttonStopPlay;
private MediaPlayer player;
public class LocalBinder extends Binder {
ListenMBC getService() {
return ListenMBC.this;
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
buttonPlaymbc1 = (Button) findViewById(R.id.buttonPlaymbc1);
buttonPlaymbc2 = (Button) findViewById(R.id.buttonPlaymbc2);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonPlaymbc1.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
stopPlayback();
playRadio1();
buttonPlaymbc1.setEnabled(false);
if(!buttonStopPlay.isEnabled()){
buttonStopPlay.setEnabled(true);
}
if(!buttonPlaymbc2.isEnabled()){
buttonPlaymbc2.setEnabled(true);
}
}
});
buttonPlaymbc2.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
stopPlayback();
playRadio2();
buttonPlaymbc2.setEnabled(false);
if(!buttonStopPlay.isEnabled()){
buttonStopPlay.setEnabled(true);
}
if(!buttonPlaymbc1.isEnabled()){
buttonPlaymbc1.setEnabled(true);
}
}
});
buttonStopPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
stopPlayback();
}
});
}
private void playRadio1() {
player = new MediaPlayer();
try {
player.reset();
player.setDataSource("http://onlineradio.globemw.net:8000");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
if (player != null) {
stopPlayback();
}
}
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer player) {
player.start();
}
});
}
private void playRadio2() {
player = new MediaPlayer();
try {
player.reset();
player.setDataSource("http://onlineradio.globemw.net:8002");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
if (player != null) {
stopPlayback();
}
}
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer player) {
player.start();
}
});
}
private void stopPlayback() {
if (player!=null) {
player.stop();
player.release();
player=null;
}
buttonStopPlay.setEnabled(false);
if(!buttonPlaymbc1.isEnabled()){
buttonPlaymbc1.setEnabled(true);
}
if(!buttonPlaymbc2.isEnabled()){
buttonPlaymbc2.setEnabled(true);
}
}
}
This is MBCRADIO.java file ...
package org.apache.android.media;
import android.app.Application;
public class MBCRADIO extends Application {
#Override
public void onCreate() {
}
#Override
public void onTerminate() {
}
}
This is my main.xml file ....
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/bg" >
<TextView
android:layout_width="fill_parent"
android:layout_height="10dp"
android:text="#string/toptext" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_weight="1">
<Button
android:id="#+id/buttonPlaymbc1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/play1" />
<Button
android:id="#+id/buttonPlaymbc2"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/play2" />
<Button
android:id="#+id/buttonStopPlay"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/stop" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center" >
<ImageView android:id="#+id/ib"
android:src="#drawable/mbc150"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="fill_parent"
android:layout_height="20dp"
android:gravity="center"
android:text="#string/copy" />
<TextView
android:layout_width="fill_parent"
android:layout_height="20dp"
android:gravity="center"
android:text="#string/copytext" />
</LinearLayout>
This code is working fine. Only thing is after opening app it going to backgroung when i click back button. Then if i open this app again, it is opening another instance. But i want to open background app to front. Please help if any body interested to this topic.
Thank You.
You need add flag of singleTop for the launch mode of the activity. Change you menifest files to add launch mode for your activity like this:
<activity
android:name=".ListenMBC"
android:label="#string/app_name"
android:launchMode="singleTop"> //This is what you need to add to you manifest
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Refer to android documentation here for more info
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