In a document based app I have created, I have a View called “TestDraw” where I can drag and drop UILables from the collectionView. On the “TestDraw”, free-drawing is also allowed. I have also set BarItems for saving the position where the user put the UILabel and the information on it so that that information can later be decoded into the card object. However, every time I open a JSON file that I think have been saved successfully, it turns out to be blank.

I have tried to print the jsonString of the saved file into the console which proves to be correct and hence shows the information is saved successfully.

Here is the code in the NumberCardsSetDocument:

class NumberCardsSetDocument: UIDocument {

var numberCardsSet: NumberCardsSet?

override func contents(forType typeName: String) throws -> Any {
    // Encode your document with an instance of NSData or NSFileWrapper
    return numberCardsSet?.json ?? Data()
}

override func load(fromContents contents: Any, ofType typeName: String?) throws {
    if let json = contents as? Data{
        numberCardsSet = NumberCardsSet(json: json)
    }else {
        print("Error trying to load NumberCards. Content is not JSON data")
    }
  }
}

Here is the code in the NumberCardsSet:

struct NumberCardsSet: Codable{
var numberCards = [CardInfo]()
struct CardInfo: Codable{
    let x: Int
    let y: Int
    let text: String
    let size: Int
}
init?(json:Data){
    if let newValue = try? JSONDecoder().decode(NumberCardsSet.self, from: json){
        self = newValue
    }else{
        return nil
    }
}
var json: Data? {
    return try? JSONEncoder().encode(self)
}
init (numberCards:[CardInfo]){
    self.numberCards = numberCards
}
}

And this is what I am trying to do to load the saved data:

class DocumentBrowserViewController: UIDocumentBrowserViewController, UIDocumentBrowserViewControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    delegate = self
    allowsPickingMultipleItems = false
    allowsDocumentCreation = true
    template = try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("UntitledHMS.json")
    if template != nil {
        allowsDocumentCreation = FileManager.default.createFile(atPath: template!.path, contents: Data() )
    }
}

var template:URL?
// MARK: UIDocumentBrowserViewControllerDelegate

func documentBrowser(_ controller: UIDocumentBrowserViewController, didRequestDocumentCreationWithHandler importHandler: @escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) {
    importHandler(template,.copy)
}

func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentsAt documentURLs: [URL]) {
    guard let sourceURL = documentURLs.first else { return }
    presentDocument(at: sourceURL)
}

func documentBrowser(_ controller: UIDocumentBrowserViewController, didImportDocumentAt sourceURL: URL, toDestinationURL destinationURL: URL) {
    presentDocument(at: destinationURL)
}

func documentBrowser(_ controller: UIDocumentBrowserViewController, failedToImportDocumentAt documentURL: URL, error: Error?) {
}

// MARK: Document Presentation
func presentDocument(at documentURL: URL) {
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let documentVC = storyBoard.instantiateViewController(withIdentifier: "DocumentMVC")
    if let trailMakingTestViewController = documentVC.contents as? DocumentViewController{
        trailMakingTestViewController.document = NumberCardsSetDocument(fileURL: documentURL)
    }
    present(documentVC,animated: true)
}
}

I think the problem probably lies in the process of decoding the information. Hoping someone can give me some clue. This is the first time I tried to build a complicated app on my own.

I am using UIWebView to load a url but my didFinishNavigation class multiple times.

I have to evaluate javascript and I had to wait for page to load complete and then have to inject JS in it but it fires multiple times.

`-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

[_webView evaluateJavaScript:js completionHandler:nil];

}`

js is the string in which I have written my JS Code

I am developing a Xamarin.Forms application for IoS and cant seem to find a package/tutorial for using google places api (can find only for android). Am i on the right path or is there any other path I should take (like Mapkits etc) thanks all

I'm using AFNetworking in my Swift app. I make a POST request using AFHTTPRequestSerializer and receive response using AFHTTPResponseSerializer. HTTP status code is 200 and I get successful response.

However, I'm not able to parse Boolean response. On Postman, the response comes as Boolean (either true or false) but I'm not able to identify response object type in my code. Please see attached image showing response object.

enter image description here

Response on Postman

enter image description here

Tried parsing it as follows but IF condition doesn't satisfy.

if let isSuccess = response as? Bool {
     print(isSuccess)
}

I get a Thread 1: breaking point 1.1 error message. I created an exception breakpoint but it still crashes on the following line.

class AppDelegate: UIResponder, UIApplicationDelegate {

Please help!

At first I was worried that expo had a custom notification system (had me thinking "coulda had a p8", if you know the commercial like that, haha). In the end, I was impressed with how direct and easy sending messages with expo's push notification service is. The only problem I ran into was in coming to realize that this will never work on a simulator. Otherwise, it's pretty spiffy really, even easier than a p8.

But I'm noticing a different pattern of behavior when I try to send a background notification. In that instance, nothing seems to be happening.

My platform is iOS, and my App component has an extension that it binds to this and then fires off only once:

extensionAPNs.js

import { Alert } from 'react-native'
import { Permissions, Notifications } from 'expo'
import AsyncStorage from '@callstack/async-storage'

import { handleNotification } from '@src/lib/APNs'

export async function registerForPushNotifications () {
  const { status } = await Permissions.getAsync(Permissions.NOTIFICATIONS)

  if (status !== 'granted') {
    const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS)
    if (status !== 'granted') {
      Alert.alert('received no permission to listen to APNs')
      return
    }
  }

  const expoToken = await Notifications.getExpoPushTokenAsync()
  Alert.alert('recieved permission to listen to APNs with token ' + expoToken)

  this.subscription = Notifications.addListener(handleNotification)

  this.setState({ expoToken })
  AsyncStorage.setItem('expoToken', expoToken)
}
import { Alert } from 'react-native'

export async function handleNotification () {
  Alert.alert(JSON.stringify(arguments))
  console.log('arguments', arguments)
}

Elsewhere, I share that token so I can message it. I noticed it wasnt working when my server sent its background message, although it does register as a success from the POST (didn't open the app, didn't add the Alert popup... even if the app was in the foreground, no popup). So I went to the PN tool and sure enough, the first "hello world" that I did worked. Immediately, it works, too.

But if I configure it like my own message, with json data, category, and content available -- and nothing else, nothing happens. Not in the foreground, not in the background. Not when closed. :frowning:

Everything works fine till I build my application for the simulator. But it started crashing only on real devices after building the same application.

After filling the details of the user my application asks for permission to allow device location. That time, in real device, it's crashing.

In the debugger I'm getting the following logs:

[Common] _BSMachError: port c00b; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND"
[Common] _BSMachError: port d07; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND"
[Common] _BSMachError: port d07; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND"

i used applyMobileFormat() in textField on .editingChanged event, when typed apply pattern exactly, but When the character wants to delete, only the numbers are deleted

extension String{
    func applyPatternOnNumbers(pattern: String) -> String {
        let replacmentCharacter: Character = "#"
        let pureNumber = self.replacingOccurrences( of: "[^۰-۹0-9]", with: "", options: .regularExpression)
        var result = ""
        var pureNumberIndex = pureNumber.startIndex
        for patternCharacter in pattern {
            if patternCharacter == replacmentCharacter {
                guard pureNumberIndex < pureNumber.endIndex else { return result }
                result.append(pureNumber[pureNumberIndex])
                pureNumber.formIndex(after: &pureNumberIndex)
            } else {
                result.append(patternCharacter)
            }
        }
        return result
    }
}

usage in .editingChaned:

let mobile = "+18004449999"
    let pattern = "+# (###) ###-####"
    let result = mobile.applyPatternOnNumbers(pattern: pattern)
    print("result \(result)") //->result +1 (800) 444-9999

the space & - , ( , ) , - chars can not to be removed

This question already has an answer here:

This might be a beginner question, but can I know the keyboard shortcut to open Object Library in Xcode 10. Thanks

I'm still new to Android Studio and I encountered a problem.

The ListView does not display immediately. I still have to click the BottomNavigationView Home so that the ListView will display.

I created an activity which is a NavigationDrawerActivity and migrated its java codes to MainActivity. I also configured the XMLs so it works properly.

Here are the codes that are 'used' in the problem.

The MainActivity.java

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);

        final BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener
                (new BottomNavigationView.OnNavigationItemSelectedListener() {

                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        Fragment selectedFragment = null;
                        switch (item.getItemId()) {
                            case R.id.navigation_home:
                                selectedFragment = HomeScreenFragment.newInstance ();
                                break;
                            case R.id.navigation_notifications:
                                selectedFragment = NotifScreenFragment.newInstance();
                                break;
                        }
                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        transaction.replace(R.id.frame_layout, selectedFragment);
                        transaction.commit();
                        return true;
                    }
                });

        Toolbar toolbar = findViewById (R.id.toolbar);
        setSupportActionBar (toolbar);

        FloatingActionButton fab = findViewById (R.id.fab);
        fab.setOnClickListener (new View.OnClickListener () {
            @Override
            public void onClick(View view) {

                Intent toPost = new Intent (MainActivity.this, PostClass.class);
                startActivity (toPost);

            }
        });

        DrawerLayout drawer = findViewById (R.id.drawer_layout);
        NavigationView navigationView = findViewById (R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle (
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener (toggle);
        toggle.syncState ();
        navigationView.setNavigationItemSelectedListener (this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById (R.id.drawer_layout);
        if (drawer.isDrawerOpen (GravityCompat.START)) {
            drawer.closeDrawer (GravityCompat.START);
        } else {
            super.onBackPressed ();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater ().inflate (R.menu.navigation_drawer, 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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId ();

        if (id == R.id.nav_profile) {

            Intent toProfile = new Intent (MainActivity.this, ProfileScreen.class);
            startActivity (toProfile);

        } else if (id == R.id.nav_home) {
            Intent toProfile = new Intent (MainActivity.this, MainActivity.class);
            startActivity (toProfile);
        }

        DrawerLayout drawer = findViewById (R.id.drawer_layout);
        drawer.closeDrawer (GravityCompat.START);
        return true;
    }
}

drawerlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_navigation_drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_navigation_drawer"
        app:menu="@menu/activity_navigation_drawer_drawer">
    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

app_bar_navigation_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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=".NavigationDrawer">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary">

            <TextView
                android:id="@+id/tabHeader"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/home"
                android:textColor="@color/colorAccent"
                android:textStyle="bold"
                android:textSize="20sp"/>

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_navigation_drawer" />

</android.support.design.widget.CoordinatorLayout>

content_navigation_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".NavigationDrawer"
    tools:showIn="@layout/app_bar_navigation_drawer">

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/navigation"
        android:layout_alignParentStart="true"
        android:layout_marginStart="0dp"
        android:layout_marginBottom="0dp"
        android:animateLayoutChanges="true" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_margin="@dimen/fab_margin"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:backgroundTint="@color/colorPrimary"
        android:outlineAmbientShadowColor="@color/colorPrimaryDark"
        android:outlineSpotShadowColor="@color/colorPrimaryDark"
        app:backgroundTint="@color/colorPrimaryDark"
        app:borderWidth="0dp"
        app:layout_constraintBottom_toTopOf="@+id/navigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:srcCompat="@drawable/icon_plus_white"
        app:useCompatPadding="true" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        app:menu="@menu/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:itemIconTint="@color/colorPrimary"
        app:itemTextColor="@color/colorPrimary"
        android:background="@color/colorAccent"
        android:elevation="10dp"
        app:elevation="10dp"
        />

</android.support.constraint.ConstraintLayout>

content_navigation_drawer.xml is where the frame_layout that is inflated located.

I want that when I open the application, the ListView of HomeScreen is inflated to frame_layout immediately and I don't have to click Home in the BottomNavigationView to display it.

Thank you for help in advance. English is not my native language, I apologize. If there need some clarifications I will be glad to answer.

The problem I experienced when (Linearlayout) was set to alignParentBottom which contained it (TextView) and then pack RelativeLayout with scrollview (so that when the Keyboard appears all the views can be seen) - However, when the Keyboard appears and the ScrollView TextView mode becomes irregular with others textview (such as Pictures).

how to fix my problem below, I want alignParentbottom to have space when the scrollview and keyboard appear.

Image https://2.bp.blogspot.com/-7oX2mpmzFas/XLxdIH6x1OI/AAAAAAAAA-g/MNL4mIr_Pr85isMBc05LNTvTyQAwimmLgCLcBGAs/s1600/Graphic1.jpg

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">

<RelativeLayout
android:id="@+id/badan"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:gravity="center_vertical"
android:padding="20dp">

<!--  Header Starts-->

<LinearLayout android:id="@+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:layout_marginTop="50dp"
android:layout_marginBottom="15dp"
android:gravity="center"
android:paddingBottom="5dip">

<!-- Logo Start-->

<ImageView android:src="@drawable/logo"
android:layout_width="100dp"
android:layout_height="100dp"/>

<!-- Logo Ends -->

</LinearLayout>

<!--  Header Ends -->

<!-- Login Form -->

<LinearLayout
android:id="@+id/loginform"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_below="@id/header">

<!--  Email Label -->

<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:padding="10dp"
android:background="@drawable/forminput"
android:inputType="textEmailAddress"
android:singleLine="true"
android:hint="Email" />

<!--  Password Label -->

<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="10dp"
android:background="@drawable/forminput"
android:singleLine="true"
android:inputType="textPassword"
android:hint="Kata Sandi"/>

<!-- Login button -->
<Button android:id="@+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:background="@drawable/button"
android:text="Login"
android:textColor="@color/white"
android:textSize="17dp"/>

<!-- Link to Registration Screen -->

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="center_horizontal"
android:orientation="horizontal">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Lupa detail informasi masuk Anda? Dapatkan bantuan untuk masuk."
android:textSize="14sp"
android:gravity="center"/>
</LinearLayout>

</LinearLayout>

<!-- Login Form Ends -->

<!-- Footer Start-->
<LinearLayout
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
android:gravity="center"
android:layout_height="wrap_content"
android:padding="15dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tidak punya akun?"
android:textSize="14sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buat akun."
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
<!-- Footer Ends -->    

</RelativeLayout>

</ScrollView>

I wish to get details about the song from the given API. For ease of debugging i have hard-coded the URL at the moment. I wish to go to the URL https://theaudiodb.com/api/v1/json/1/searchtrack.php?s=coldplay&t=paradise&s=coldplay&t=paradise and fetch strDescriptionEN. I am mentioning both the ways i have tried doing this..

I know the exception but i dont know how to fix that.

This is method 1 that i have tried.

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.JsonReader;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
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 Lyrics_Details extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lyrics__details);
        final String trackname=getIntent().getStringExtra("tracknamedata");
        new RetriveLyrics().execute();
    }
    class RetriveLyrics extends AsyncTask<Void,Void,String>{
        @SuppressLint("WrongThread")
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast toast = Toast.makeText(Lyrics_Details.this, "In pre execute",Toast.LENGTH_SHORT);
            toast.show();
        }
        @Override
        protected String doInBackground(Void... voids) {
            int num=0;
            String value="lawda nahi millaaa";
            try {
                URL audiodb = new URL("http://theaudiodb.com/api/v1/json/1/searchtrack.php?s=Coldplay&t=Paradise");
                HttpURLConnection myConnection =(HttpURLConnection) audiodb.openConnection();
                num++;
                InputStream responseBody = myConnection.getInputStream();
                num++;
                InputStreamReader responseBodyReader = new InputStreamReader(responseBody);
                num++;
                JsonReader jsonReader = new JsonReader(responseBodyReader);
                num+=10;
                jsonReader.beginObject();
                num+=50;
                while (jsonReader.hasNext())
                {
                    num++;
                    String key = jsonReader.nextName();
                    if (key.equals("idArtist")) {
                        value = jsonReader.nextString();
                        return value;
                    } else {
                        jsonReader.skipValue();
                        num++;
                    }
                }
                jsonReader.close();
                myConnection.disconnect();
            }
            catch (IOException e) {
                e.printStackTrace();
                num=num+400;
            }
            value=value+num;
            return value;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            TextView TVdetails= findViewById(R.id.TVdetails);
            TVdetails.setText(s);
            Toast toast = Toast.makeText(Lyrics_Details.this, "In post execute",Toast.LENGTH_SHORT);
            toast.show();
        }
    }
}

This is method 2 that i have tried

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.JsonReader;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
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 Lyrics_Details extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lyrics__details);
        final String trackname=getIntent().getStringExtra("tracknamedata");
        final String artistname=getIntent().getStringExtra("artistnamedata");
        new RetriveLyrics().execute();
    }
    class RetriveLyrics extends AsyncTask<Void,Void,String>{
        @SuppressLint("WrongThread")
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast toast = Toast.makeText(Lyrics_Details.this, "In pre execute",Toast.LENGTH_SHORT);
            toast.show();
        }
        @Override
        protected String doInBackground(Void... voids) {
            int num=0;
            String value="lawda nahi millaaa";
            try {
                URL audiodb = new URL("http://theaudiodb.com/api/v1/json/1/searchtrack.php?s=Coldplay&t=Paradise");
                HttpURLConnection myConnection =(HttpURLConnection) audiodb.openConnection();
                num++;
                InputStream stream = new BufferedInputStream(myConnection.getInputStream());
                num++;
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
                num++;
                StringBuilder builder = new StringBuilder();
                num++;
                String inputString;
                while ((inputString = bufferedReader.readLine()) != null) {
                    builder.append(inputString);
                }
                num+=1;
                JSONObject topLevel = new JSONObject();
                num+=200;
                JSONObject main = topLevel.getJSONObject("0");
                num++;
                value = String.valueOf(main.getDouble("strDescriptionEN"));
                num++;
                myConnection.disconnect();
            }
            catch (IOException e) {
                e.printStackTrace();
                num=num+400;
            }
            value=value+num;
            return value;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            TextView TVdetails= findViewById(R.id.TVdetails);
            TVdetails.setText(s);
            Toast toast = Toast.makeText(Lyrics_Details.this, "In post execute",Toast.LENGTH_SHORT);
            toast.show();
        }
    }
}

The output i am getting is lawda nahi millaaa214 i.e. the exception is at line JsonReader.beginObject() in method 1. The output in Method 2 is lawda nahi millaaa605 i.e.the exception is at line JSONObject main = topLevel.getJSONObject("artists");

And the expected result is... "\"Paradise\" is a song ... China\"."

I am prototyping a music player for android. I want to have some stereo delay between the left and right audio channels of the span of 10 to 100 ms. I am planning to use google vr audio api (resonance-audio) with exoplayer but i think that may be overkill on the processor for just music playback. So it is possible to achieve this using only aaudio and exoplayer?

I m using exoplayer in recylcerview for video player, its working fine and i also implement fullscreen button into exoplayer for fullscreen viewing with the help of Dialog. Before starting fullscreen dialog i am removing view from recyclerview and when returning back from fullscreen adding view back into recycler but i am not able to add view back at right place in recyclerview.

Exoplayer Class

public class ExoPlayer_Main {

    public static final String TAG="###ExoPlayer###";
    MediaSource mediaSource;
    Context context;
    PlayerView playerView;
    SimpleExoPlayer player;
    boolean playWhenReady=false;
    long playbackPosition;
    int currentWindow;
    int newPlayerState=1;
    List<Uri> mediaList=new ArrayList<>();
    ComponentListener componentListener=new ComponentListener();
    private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
    private FrameLayout mFullScreenButton;
    //Fullscreen Setting
    ImageView mFullScreenIcon;
    private boolean mExoPlayerFullscreen = false;
    private Dialog mFullScreenDialog;




    public ExoPlayer_Main(Context context, PlayerView playerView) {
        this.context = context;
        this.playerView=playerView;

    }

    public void initializePlayer(Uri uri,int mediaType){
        Log.d(TAG,"Init Player Calling ");
        if (player==null){
            player = ExoPlayerFactory.newSimpleInstance(context);           
            player.clearVideoSurface();
            player.addListener(componentListener);
            player.setPlayWhenReady(playWhenReady);
            player.seekTo(currentWindow,playbackPosition);
            player.clearVideoSurface();
            mediaSource = buildMediaSourceNew(uri,mediaType);
            playerView.setPlayer(player);
            player.prepare(mediaSource);
            initFullscreenButton();
        }


    }



    private MediaSource buildMediaSourceNew(Uri uri,int buildType){

            DataSource.Factory datasourceFactroy = new DefaultDataSourceFactory(context, Util.getUserAgent(context,"Elaxer"));
            MediaSource mediaSource = new ExtractorMediaSource.Factory(datasourceFactroy).createMediaSource(uri);
            return mediaSource;      
    }


    public void releasePlayer() {
        Log.d(TAG,"Release Player "+player);
        if (player != null) {
            Log.d(TAG,"Player Is Not Null Now Releasing ");
            player.stop();
            player.setPlayWhenReady(false);
            playbackPosition = player.getCurrentPosition();
            currentWindow = player.getCurrentWindowIndex();
            playWhenReady = player.getPlayWhenReady();
            player.release();
            mediaSource = null;
            player = null;
        }

    }




    private class ComponentListener implements Player.EventListener {


        @Override
        public void onTimelineChanged(Timeline timeline, @Nullable Object manifest, int reason) {

        }

        @Override
        public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelectionArray) {
            for (int i = 0; i < trackGroups.length; i++) {
                TrackGroup trackGroup = trackGroups.get(i);
                Log.d(TAG,"On Track Change Track Group "+trackGroup);
                for (int j = 0; j < trackGroup.length; j++) {
                    Metadata trackMetadata = trackGroup.getFormat(j).metadata;
                    if (trackMetadata != null) {
                        // We found metadata. Do something with it here!
                        Log.d(TAG,"On Tack Changed "+trackMetadata.get(j));

                    }
                }
            }
        }

        @Override
        public void onLoadingChanged(boolean b) {

        }

        @Override
        public void onPlayerStateChanged(boolean b, int i) {

        }

        @Override
        public void onRepeatModeChanged(int i) {

        }

        @Override
        public void onShuffleModeEnabledChanged(boolean b) {

        }

        @Override
        public void onPlayerError(ExoPlaybackException e) {

        }

        @Override
        public void onPositionDiscontinuity(int i) {

        }

        @Override
        public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {

        }

        @Override
        public void onSeekProcessed() {

        }
    }


    private void initFullscreenButton() {


        PlayerControlView controlView = playerView.findViewById(R.id.exo_controller);
        mFullScreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
        mFullScreenButton = controlView.findViewById(R.id.exo_fullscreen_button);
        mFullScreenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mExoPlayerFullscreen){
                    openFullscreenDialog();
                }else{
                    closeFullscreenDialog();
                }

            }
        });

    }
    private void openFullscreenDialog() {
        initFullscreenDialog();
        ((ViewGroup)playerView.getParent()).removeView(playerView);
        player.setPlayWhenReady(false);
        mFullScreenDialog.addContentView(playerView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mFullScreenIcon.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_fullscreen_skrink));
        mExoPlayerFullscreen = true;
        mFullScreenDialog.show();
    }


    private void closeFullscreenDialog() {

        ((ViewGroup) playerView.getParent()).removeView(playerView);
        FrameLayout playerAdd =  ((Activity)context).findViewById(R.id.main_media_frame);
        playerAdd.addView(playerView);
        mExoPlayerFullscreen = false;
        mFullScreenDialog.dismiss();
        mFullScreenIcon.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_fullscreen_expand));
    }

    private void initFullscreenDialog() {

        mFullScreenDialog = new Dialog(context, android.R.style.Theme_Black_NoTitleBar_Fullscreen) {
            public void onBackPressed() {
                if (mExoPlayerFullscreen)
                    closeFullscreenDialog();
                super.onBackPressed();
            }
        };
    }

Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:emojicon="http://schemas.android.com/apk/res-auto"
    android:id="@+id/chatAdapter_Parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/Single_Item_Chat_ImageView"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_marginLeft="2dp"
        android:src="@drawable/common_google_signin_btn_text_dark"/>
    <FrameLayout
        android:id="@+id/main_media_frame"
        android:layout_width="match_parent"
        android:layout_height="175dp"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="5dp"
        android:layout_toRightOf="@id/Single_Item_Chat_ImageView"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="5dp">

        <com.google.android.exoplayer2.ui.PlayerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:show_timeout="2000"
            app:fastforward_increment="30000"
            app:rewind_increment="30000"
            android:layout_toRightOf="@id/Single_Item_Chat_ImageView"
            android:id="@+id/Single_Item_Chat_User_Posted_Video"
            />
    </FrameLayout>

</RelativeLayout>

I have 2 question here

  1. How can i maintain single instance in recylcerview of Exoplayer.
  2. How to close full screen dialog and add view back into recyclerview at right place.

This question already has an answer here:

I can share using SMS and Google Drive but can't share with Messenger (it says "Unable to send. Try again later." and Gmail on my app.

The audio I want to send is located in "app/res/raw/audio.mp3". That's the code I'm using:

@Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM,
                        Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.audio));
                intent.setType("audio/mp3");
                startActivity(Intent.createChooser(intent, "Share..."));

            }});

I also added in AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

I wanted to be able to share my mp3 audio file through Messenger and Gmail but I'm only able to send using SMS and Google Drive. Please help me.

This question already has an answer here:

I use an AndroidService to download a picture from a specific path. As I have to check whether the file already exists, I have written a helper class that checks if the path can found. If I use this part of the code in the Service it works fine, however, if I use the code in the helper class and call the helper class method in the Service the code always throws an exception.

Service Class:

ArrayList<String> paths = helper.getFilledFileNamesArray();

//Run through all pictures

for (String p : paths)
{

  java.net.URL url = new URL(helper.webUrl + p);

  stream = url.openConnection().getInputStream(); //No execption is thrown
  ...           
}

In the helper class:

ArrayList<String> fileNames = getFilledFileNamesArray();

for (String p : fileNames)
{

 //Try to open files
 java.net.URL url = new URL(this.webUrl + p);
 stream = url.openConnection().getInputStream(); //Execption is thrown

}

The execption thrown:

android.os.NetworkOnMainThreadException

((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[0] = {StackTraceElement@11019} "android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[1] = {StackTraceElement@11020} "java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[2] = {StackTraceElement@11021} "java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[3] = {StackTraceElement@11022} "java.net.InetAddress.getAllByName(InetAddress.java:1154)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[4] = {StackTraceElement@11023} "com.android.okhttp.Dns$1.lookup(Dns.java:39)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[5] = {StackTraceElement@11024} "com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[6] = {StackTraceElement@11025} "com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[7] = {StackTraceElement@11026} "com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[8] = {StackTraceElement@11027} "com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[9] = {StackTraceElement@11028} "com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[10] = {StackTraceElement@11029} "com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[11] = {StackTraceElement@11030} "com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[12] = {StackTraceElement@11031} "com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[13] = {StackTraceElement@11032} "com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[14] = {StackTraceElement@11033} "com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[15] = {StackTraceElement@11034} "com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[16] = {StackTraceElement@11035} "com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[17] = {StackTraceElement@11036} "com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:26)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[18] = {StackTraceElement@11037} "com.posseggs.an07_weatheranimation_possegger.FileNameHelper.findValidPaths(FileNameHelper.java:100)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[19] = {StackTraceElement@11038} "com.posseggs.an07_weatheranimation_possegger.MainActivity.downloadedFilesExists(MainActivity.java:117)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[20] = {StackTraceElement@11039} "com.posseggs.an07_weatheranimation_possegger.MainActivity.onCreate(MainActivity.java:145)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[21] = {StackTraceElement@11040} "android.app.Activity.performCreate(Activity.java:7136)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[22] = {StackTraceElement@11041} "android.app.Activity.performCreate(Activity.java:7127)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[23] = {StackTraceElement@11042} "android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[24] = {StackTraceElement@11043} "android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[25] = {StackTraceElement@11044} "android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[26] = {StackTraceElement@11045} "android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[27] = {StackTraceElement@11046} "android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[28] = {StackTraceElement@11047} "android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[29] = {StackTraceElement@11048} "android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[30] = {StackTraceElement@11049} "android.os.Handler.dispatchMessage(Handler.java:106)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[31] = {StackTraceElement@11050} "android.os.Looper.loop(Looper.java:193)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[32] = {StackTraceElement@11051} "android.app.ActivityThread.main(ActivityThread.java:6669)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[33] = {StackTraceElement@11052} "java.lang.reflect.Method.invoke(Native Method)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[34] = {StackTraceElement@11053} "com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)"
((StackTraceElement[])((NetworkOnMainThreadException)ex).stackTrace)[35] = {StackTraceElement@11054} "com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)"

I have recently downloaded Android Studio 3.4. I started a new project, but it doesn't work as it keeps giving the error : Unknown host 'dl.google.com'. You may need to adjust the proxy settings in Gradle

I have tried : 1. Using the latest Gradle Release (5.4) 2. Setting Auto-detect proxy 3. Deleting the gradle folder from - C:\Program Files\Android\Android Studio\gradle and restarting Android studio after that so that new files are downloaded by android Studio itself.

This is from my build.gradle file :

buildscript 
{
    repositories {
        google()
        jcenter()

    }
    dependencies 
{
        classpath 'com.android.tools.build:gradle:3.4.0'
    }
}

allprojects 
{
    repositories {
        google()
        jcenter()

    }
}

I want to pause a speech while text to speech is speaking and continue from the same position where i had stop or pause the speech and play from the previously paused state or position.

I have been using Apachecommonstext lib that helps in String manipulation more then what core java offers.

So my question is how do i gain this functionality.

Map<String, String> myMap = nee HahMap<>();
myMap.put("text",main_input.getText().toString());
String template = "${text}";
StringSubstitutor substitutor = new Substitutor(myMap);
String data = substitutor.replace(template);

textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null, null);

I am using the above code to speak right now.

I want to set different colored and width borders to top/bottom/start/end of a layout in android, i've tried the following but it didnt work.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
        android:start="5dp">
    <shape android:shape="rectangle">
        <solid android:color="#FF7539"/>
    </shape>
</item>

<item
        android:top="1dp">
    <shape android:shape="rectangle">
        <solid android:color="#000000"/>
    </shape>
</item>

<item
        android:bottom="1dp">
    <shape android:shape="rectangle">
        <solid android:color="#000000"/>
    </shape>
</item>

<item
        android:end="1dp">
    <shape android:shape="rectangle">
        <solid android:color="#000000"/>
    </shape>
</item>

<item
        android:top="1dp" android:bottom="1dp" android:start="5dp" android:end="1dp">
    <shape android:shape="rectangle">
        <solid android:color="#ffffff"/>
    </shape>
</item>
</layer-list>

Any help is appreciated.

I have a spinner of cities with default value "Other City". If the user can't find his city, when he selects Other City, a textInput (Your city) is shown. When the user enters his city name there and Clicks the button Register, the getText().toString() doesn't return the value. And also when the field is empty even though I have written validation code, it doesn't work.

Log.i("cities[0]", "("+cities[0]+")");
Log.i("regOtherCity", "("+(regUserOtherCity.getText().toString())+")");
if (userCity.equals(cities[0]) && TextUtils.isEmpty(regUserOtherCity.getText().toString()) )
{
           error = true;
            Log.i("checkerror", "("+cities[0]+")");
            regUserOtherCity.setError("Enter Your City");
            regUserOtherCity.requestFocus();
        }
        else if (userCity.equals(cities[0]))
            userCity = regUserOtherCity.getText().toString();
        Log.i("cities[0]", "("+cities[0]+")");
        Log.i("regOtherCity", "("+userCity+")");

I have tried debugging by using Logcat, the output is here for the time when the user enters 'my city' in the text input.

I/cities[0]: (Other City)
I/regOtherCity: (my city)
I/cities[0]: (Other City)
I/regOtherCity: ()