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.
Related
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>
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>
When i run my app in my device [which runs on 7.1] The app runs well but when i run it on my opo which runs on 4.4 it crashed and when i try to run it on a android 5.0 device it gave app cannot install error
I've build>generate signed apk and have used that
I'm basically new to all this so if anyone can help me out what the issue is i would be glad
my activity_main code is
<?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.bingobean.pitchblack.MainActivity"
android:weightSum="1">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="center"
android:src="#drawable/android"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="Pitch black"
android:textColor="#ffffff"
android:textSize="50sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="118dp"
android:layout_height="109dp"
android:layout_marginTop="144dp"
android:text="Hit it!"
android:textSize="24sp"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
</RelativeLayout>
My mainactivity is
package com.bingobean.pitchblack;
import android.app.WallpaperManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Button btn;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
img = (ImageView) findViewById(R.id.imageView1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WallpaperManager wallmgr =
WallpaperManager.getInstance(getApplicationContext());
try {
wallmgr.setResource(+ R.drawable.android);
} catch (IOException e){
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Wallpaper is set",
Toast.LENGTH_SHORT).show();
}
});
}
}
My Androidmanifest is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bingobean.pitchblack">
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<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>
check your app level build.gradle file in , in that file You have these two attributes :
minSdkVersion 16
targetSdkVersion 23 this
// these are api levels
Change them to according to your requirement .
Ditto to what Hamza said, you must have set your min and target api to not be compatible with kitkat. as for the app not installed, that is either 1: you have an app with same package name installed, 2: the LAUNCH and DEFAULT intents aren't set (they are it seems), or 3: it somehow got corrupted. Please post your logcat for when it crashes. Root your phone and download LogCat.
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