Android Questions & Answers


 Question by : adamhala007March 13, 2017 21:06

How to sell apps on Google Play without having a company?


I have signed up to Google Play some days ago to upload free apps but also to sell apps. I have paid 25 dollars for registration. When I wanted to upload an app for selling, I have realised that I need to set up a Google Payments merchant account. But it requires a business name and another pieces of information about my business. The problem is, that I do not own a company. When I click on Account type, it doesn't matter, if I choose individual or business, in both case it requires pieces of information about business.

I don't know, if the problem is that I am from Slovakia.

Could anybody help me, how to sell apps without owning a company? It is very annoying that they charge me 25 dollars but don't allow me to sell apps.

View answer

 Question by : Vladimir LitovkinMarch 13, 2017 21:46

Difference between Activity.class and Class class


I was creating notification Intent that opens one of two activities depending on condition. Worked as expected since I have all intent flags required for this.

I tried to optimize my method flow by extracting new Intent and Class, so optimized code looked like this:

Class ActivityClass;

if (siteId > 0) {
   //...
   ActivityClass = DetailActivity.class;
} else {
   //...
   ActivityClass = MainActivityWithMenu.class;
}

Intent notificationIntent = new Intent(appContext, ActivityClass);

But then my notification stopped opening activities, so I changed it to:

Intent notificationIntent = null;

if (siteId > 0) {
    notificationIntent = new Intent(appContext, DetailActivity.class);
} else {
    notificationIntent = new Intent(appContext, MainActivityWithMenu.class);
}

Second version works without any problems, but I was wondering what is the difference between Activity.class and Class class and why first snippet won't work with Intent?

Whole function:

String title = "Upcoming site:";


    Intent notificationIntent = null;

    if (siteId > 0) {
        pref.setNewVar("notificationSiteId", String.valueOf(siteId));
        notificationIntent = new Intent(appContext, DetailActivity.class);
    } else {
        notificationIntent = new Intent(appContext, MainActivityWithMenu.class);
    }


    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationIntent.putExtra("siteId", siteId);
    PendingIntent pendingIntent = PendingIntent.getActivity(appContext, 0,
            notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Notification.Builder nBuilder = new Notification.Builder(appContext)
            .setContentTitle("Neeco - " + title)
            .setContentText(text)
            .setSmallIcon(R.drawable.clock_start)
            .setContentIntent(pendingIntent);

    boolean updateNotification = true;
    if (pref.getVar("notificationText") != null && !pref.getVar("notificationText").equals(text)) {
        Log.d(TAG, "New text in notification - " + text);
        nBuilder.setSound(alarmSound);
        nBuilder.setPriority(priority);
        pref.setNewVar("notificationText", text);
    } else if (pref.getVar("notificationText") == null) {
        nBuilder.setSound(alarmSound);
        nBuilder.setPriority(priority);
        pref.setNewVar("notificationText", text);
    } else {
        updateNotification = false;
    }

    if (updateNotification) {
        Notification notification = nBuilder.build();
        NotificationManager mNotificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(Config.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);
    }

View answer

 Question by : robMarch 13, 2017 20:50

Change Button Drawable Programmatically


I have a button with drawable left:

<Button
    android:id="@+id/post_feeling_btn"
    android:background="@color/white"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="4dp"
    android:drawableLeft="@drawable/feeling_btn"
    android:gravity="left|center_vertical"
    android:textColor="@color/gray"
    android:text="Sentimento"/>

In my on resume method, I change the button's text programmatically:

Button setFeeling;
FeelingButton selectedFeeling;

@Override
public void onResume() {
    super.onResume();
    selectedFeeling = ((FeedActivity)getActivity()).getSelectedFeeling();
    if(selectedFeeling != null){
        setFeeling.setText(selectedFeeling.getFeeling());
    }
}

Is there a way to change my drawable left and set the image in the same method, using the image I have in my selectedFeeling object? I'm looking for something like:

setFeeling.setDrawable();

View answer

 Question by : PoTTiiMarch 13, 2017 20:54

React Nativ Networking Unexpected Token in Function


I am currently trying to learn React Native, but I already struggle in the Networking Part of the Tutorial.

This is the code:

import React, { Component } from 'react';
import { AppRegistry, Text, TextInput, View } from 'react-native';

class App extends Component {
    function getMoviesFromApiAsync() {
        return fetch('https://facebook.github.io/react-native/movies.json')
            .then((response) => response.json())
            .then((responseJson) => {
                return responseJson.movies;
            })
            .catch((error) => {
                console.error(error);
            });
    }


    render() {
        getMoviesFromApiAsync();
    };
}

AppRegistry.registerComponent('testproject', () => App);

And I get the following error:

enter image description here

In my case Line 5, Char 10 would be: function so it expects something else after funct.

View answer

 Question by : Azeem HaiderMarch 13, 2017 20:01

Filter Log from console in Android


I'm new in android and I'm using android studio to build app. Sometimes I need to check variable values I set log for them but It's very difficult to find a single log line out of too many lines So, I need to filter the logs.

  Log.i("Some info", "Show some thing here"); 

I'm using Android 2.2.3. In this studio I'm not able to find any filter Here is image of console. enter image description here

View answer

 Question by : thrashing mooseMarch 13, 2017 20:35

Multiple buttons appearing on my list (Android Studio to do list app)


I've been trying to make a to-do list app using android studio. The intention is an 'add new task' button at the top which opens a dialog through which I can enter a new task. The task then appears in the list below the button.

The issue is that the button keeps appearing after every task on the list (the duplicate buttons are unclickable)

screenshot of problem

Here is my code:

public class ListActivity extends Activity {
    // Declare variables

    Button button;
    private TaskDbHelper mHelper;
    private ArrayAdapter<String> mAdapter;
    private ListView mTaskListView;


    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.activity_list);

        // Locate the button in activity_main.xml
        button = (Button) findViewById(R.id.NewTaskButton);
        mHelper = new TaskDbHelper(this);
        mTaskListView = (ListView) findViewById(R.id.listview);

        updateUI();
        NewMethod();
    }



    public void NewMethod() {
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                final EditText taskEditText = new EditText(ListActivity.this);
                AlertDialog alertDialog = new AlertDialog.Builder(ListActivity.this).create();
                alertDialog.setTitle("Add a new item");
                alertDialog.setMessage("What item would you like to add?");
                alertDialog.setView(taskEditText);
                alertDialog.setButton("Add item", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // here you can add functions
                        String task = String.valueOf(taskEditText.getText());
                        SQLiteDatabase db = mHelper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                        db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
                                null,
                                values,
                                SQLiteDatabase.CONFLICT_REPLACE);
                        db.close();
                        updateUI();
                    }
                });


                alertDialog.show();  

            }

        });
    }

    private void updateUI() {
        ArrayList<String> taskList = new ArrayList<>();
        SQLiteDatabase db = mHelper.getReadableDatabase();
        Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
                new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
                null, null, null, null, null);
        while (cursor.moveToNext()) {
            int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
            taskList.add(cursor.getString(idx));
        }

        if (mAdapter == null) {
            mAdapter = new ArrayAdapter<>(this,
                    R.layout.activity_list,
                    R.id.task_title,
                    taskList);
            mTaskListView.setAdapter(mAdapter);
        } else {
            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();
        }

        cursor.close();
        db.close();
    }
}

Here is the xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff">

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ffffff"
        android:divider="#C2AF00"
        android:dividerHeight="3sp"
        android:layout_below="@+id/task_title"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="14dp" />

    <TextView
        android:id="@+id/task_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello"
        android:textSize="20sp"
        android:layout_below="@+id/NewTaskButton"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="32dp" />

    <Button
        android:id="@+id/NewTaskButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/background_light"
        android:text="@string/NewTaskButton"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        android:textColor="#0089BF"
        android:textSize="18sp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="30dp"/>

</RelativeLayout>

View answer

 Question by : ACAC94March 13, 2017 20:01

Parse Json data to extract an array from a object


    {
      "total_hits": 20277,
  "max_score": 10.676512,
  "hits": [
    {
      "_id": "513fceb375b8dbbc21000022",
      "fields": {
        "item_name": "Cheddar Cheese - 1 cup, diced",
        "brand_name": "USDA",
        "nf_calories": 531.96,
        "nf_total_fat": 43.74
      }
    },
    {
      "_id": "513fceb375b8dbbc2100001d",
      "fields": {
        "item_name": "Cheddar Cheese - 1 slice (1 oz)",
        "brand_name": "USDA",
        "nf_calories": 112.84,
        "nf_total_fat": 9.28
      }
    }
  ]
}

the above is my json returned from an api

 JSONObject raintopLevel = new JSONObject(rainbuilder.toString());

                      String listArray = raintopLevel.getString("hits");

I am returning that a JSON object "hits" using the code attached what i want to do however is access the "fields" array in side this object but i have been unable to do this any help is apprecited

thanks in advance

View answer

 Question by : GAlexMESMarch 13, 2017 19:43

How to use Google API Keys


First of all: Everythig is working at the moment. I just want your opinion for improvements.

I am currentyl developing an Android Application, that needs access to different Google APIs. So I created a API key and made a App restioction. I used that API Key inthe google_maps_api.xml to authentificate my App for the Google Maps API.

I then needed the Google Directions API. As far as I know the only way to acces it, is via HTTP request. The HTTP request needs the API key in it. Now the problem is, that my API key is App restricted. That means, it will not work with the HTTP request. I created a second API Key and removed the restriction to solve that problem at the moment. But that is not a good solution in my opinion.

I also found this SO Question from 2016, which has no answer but is facing the same problem.

View answer

 Question by : Nathiel PaulinoMarch 13, 2017 19:01

Google maps zoom in camera is not working Android


I just have a basic Google Maps project and the maps works fine, the thing is, when I Choose the Lat and Long, it doesn't shows the "Zoom Animation" even that are comment to add a marker to move the camera, and I don't know why is not working.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng location = new LatLng(DB_LAT, DB_LONG);
        mMap.addMarker(new MarkerOptions().position(location).title("CEP"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
    }

View answer

 Question by : Lucky_girlMarch 13, 2017 20:11

Picture doesn't display in react native (Android)


I just have started to learn React Native, and I'm following official tutorial, both in my emulator and phone (Android), image doesn't appear, just empty white screen. So my question, why it doesn't displayed on the screen? P.S: internet connection works fine.

import React, { Component } from 'react';
import { AppRegistry, Image } from 'react-native';

    class Bananas extends Component {
      render() {
        let pic = {
          uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
        };
        return (
          <Image source={pic} style={{width: 193, height: 110}}/>
        );
      }
    }

    AppRegistry.registerComponent('Bananas', () => Bananas);

View answer

 Question by : Alex REDMarch 13, 2017 19:23

Android default drawable over custom one


I created custom drawable for Switch but when I apply it to switch item using android:drawableRight="@drawable/switch_selector" it looks like this: enter image description here enter image description here

How to get rid of those default view? Can anyone help me? Thanks in advance!

View answer

 Question by : Crowley91tMarch 13, 2017 18:27

Query to get values between two dates


I'm looking to create this query but nothing.

I need to get some values between two dates.

MY table contain id, value, startdata, enddata.

id=1; value=x; startdata=2017-03-12; enddata=2017-03-19

startdata and enddata are DATA Type.

My query :

SELECT * FROM listino where  startdata>='2017-03-13' AND enddata<='2017-03-13' 

but no work. how to get value from this table?

View answer

 Question by : SimonMarch 13, 2017 18:17

Update/access Progressbar, TextView from a Service


I have an activity A which has a progressbar and a textview.

If user clicks a button a service is being started (ServiceB), I am trying to find a way how to update the progressbar in Activity A from the ServiceB and at the same time set the (progress) text in the Textview in Activity A.

I looked around on Google and Stackoverflow and I think I found a way to do it as described here

but I am having difficulties to implement this, any help is highly appreciated.

PS: don`t downvote, I know UI should not be directly accessed from a Service, so I am looking for a way to do it right.

Some relevant code:

Activity A:

@EActivity(R.layout.downloads_activity)
public class DownloadsActivity extends BaseActivity {

@ViewById(R.id.progress_text)
TextView progresstxt;

@ViewById(R.id.progressdownload)
ProgressBar downloadprogress;

// Update Progressbar and set Text sent from ServiceB
}

ServiceB:

public class ServiceB extends IntentService {
...

@Override
    public void onProgress(DownloadRequest request, long totalBytes, long downloadedBytes, int progress) {
        int id = request.getDownloadId();

        if (!isActive) {
            downloadManager.cancel(downloadId1);
            deleteCancelledFile.deleteOnExit();
        } else if (id == downloadId1) {
            // How to update progressbar and textview of Activity A?
            progresstxt.setText("Downloading: " + progress + "%" + "  " + getBytesDownloaded(progress, totalBytes));
            downloadprogress.setProgress(progress);
        }
    }
    ...
}

View answer

 Question by : Code-ApprenticeMarch 13, 2017 17:59

Android Studio does not detect Android device on Windows 10


I am setting up a Android development environment on a new Windows 10 laptop. I have done this many times on other machines with other operating systems, but this is the first time with Windows 10. The problem is that Android Studio cannot detect my device (LG Zone 3) after I connect it via USB. Note that I have previously used this device for development on an Arch Linux desktop.

I have downloaded Android Studio and created several AVDs. I can run my app and tests on those just fine. However, my hardware device is not listed in the selection dialog.

Here are some things I have tried:

  • Check that the USB drivers are installed.
  • Restart ADB from the Android Monitor window in Android Studio
  • Restart ADB from the command line with adb kill-server and adb start-server.
  • Quit Android Studio and restart it.
  • Unplug the device, turn off USB debugging, and turn it back on.
  • Plug device into a different USB port.
  • Switch device connection settings to Charge Only and then back to MTP.

What other trouble-shooting steps can I follow to get my device to work?

View answer

 Question by : Sahaj RanaMarch 13, 2017 20:36

How can I use Firebase Functions to send FCM to user?


Firebase currently rolled out Firebase Functions to add server side code

Firebase Functions

I was wondering if there could be a way to call FCM notifications through those functions when there is some change in database.

View answer

 Question by : Muhammed AlmazMarch 13, 2017 17:42

Android Sqllite is it today


This my Table codes

CREATE TABLE  InformationTable"
            + "(ID INTEGER, "
            + " ConfirmDate TEXT , "
            +" Counter INTEGER DEFAULT 99999"
            +" )";

I want to a select query about InformationTable. I want to create query like this ;

Select * from InformationTable where datetime(ConfirmDate) IS IT TODAY()

How can i do it ?

View answer

 Question by : albMarch 13, 2017 17:50

How to send values from a selected item on a json listview to another activity?


I'm making an app that gets countries data (name, latitude, longitude, ...) from JSON and creates a listview, where each item is a different country.

That part is working but, every time I click on a item it opens the MapActivity, with the map centered in that country. The problem is that I can't send the coordinates from the MainActivity to the MapsActivity.

public class TodasAsCategorias extends AppCompatActivity {

private String TAG = TodasAsCategorias.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://*************/api/continent/any/country/all?id=siF1uXXEsltXOi5CWlSIzy7EABlnE5iF33bnNmfAHJiYXYNmjY";
ArrayList<HashMap<String, String>> listaPaises;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_todas_as_categorias);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Categorias");

    listaPaises = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list);
    new GetPaises().execute();
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    menu.findItem(R.id.spinner_cat).setVisible(false);
    menu.findItem(R.id.spinner_pais).setVisible(false);
    return true;
}

private class GetPaises extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(TodasAsCategorias.this);
        pDialog.setMessage("Aguarde...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        HttpHandler sh = new HttpHandler();
        final String jsonStr = sh.makeServiceCall(url);
        Log.e(TAG, "Response from URL: " + jsonStr);
        if (jsonStr != null) {
            try {
                JSONArray array = new JSONArray(jsonStr);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonObject = array.getJSONObject(i);
                    JSONArray paises = jsonObject.optJSONArray("paises");
                    if (paises != null) {
                        for (int j = 0; j < paises.length(); j++) {
                            JSONObject jsonObject1 = paises.getJSONObject(j);

                            String K_PAIS = jsonObject1.getString("K_PAIS");
                            String Designacao = jsonObject1.getString("Designacao");
                            String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
                            String Coord_LAT = jsonObject1.getString("Coord_LAT");
                            String Coord_LONG = jsonObject1.getString("Coord_LONG");
                            String Coord_Zoom = jsonObject1.getString("Coord_Zoom");

                            HashMap<String, String> pais = new HashMap<>();

                            pais.put("K_PAIS", K_PAIS);
                            pais.put("Designacao", Designacao);
                            pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
                            pais.put("Coord_LAT", Coord_LAT);
                            pais.put("Coord_LONG", Coord_LONG);
                            pais.put("Coord_Zoom", Coord_Zoom);

                            listaPaises.add(pais);
                        }
                    }
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }

        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
                }
            });
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing()) {
            pDialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter(TodasAsCategorias.this, listaPaises, R.layout.list_item, new String[]{ "Designacao","Coord_LAT", "Coord_LONG", "Coord_Zoom"},
                new int[]{R.id.Designacao,R.id.Lat, R.id.Long, R.id.Zoom});
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> pare, View view, int position, long id) {
                Intent intent = new Intent(TodasAsCategorias.this, MapsActivity.class);

                startActivity(intent);
            }
        });
    }
}
}

View answer

 Question by : Coderszone techMarch 13, 2017 17:28

How Can i implement Intent Into Listview


Here am got listview into the tab fragment. now i want to start new activity according to the list item. How can i implement intent activity for the following code.

public class TabFragment1 extends Fragment {


public TabFragment1(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_tab_fragment1, container, false);

    String[] menuItems = {"list1","list2","list3"};
    ListView listView =(ListView) view.findViewById(R.id.listView);

    ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(
            getActivity(),
            android.R.layout.activity_list_item,
            menuItems
    );
    listView.setAdapter(listViewAdapter);
    return view;
}

}

View answer

 Question by : MichaelMarch 13, 2017 18:54

Cannot find symbol variable, android studios


I am following the documentation on web views on this page.

https://developer.android.com/guide/webapps/webview.html.

But I can't for the life of me figure out why I get the following error, when I add the last piece(public boolean onKeyDown) of the code. Do I need to declare this variable in the top of the file?

"cannot find symbol variable myWebView"

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView myWebView = (WebView) findViewById(R.id.webView);
        myWebView.addJavascriptInterface(new WebAppInterface(this), "android");
        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.loadUrl("http://example.nl");
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }

}

View answer

 Question by : Son_NguyenMarch 13, 2017 16:43

Constraints Layout of Android Studio doesn't work correctly


I'm new in Android, i just create my first simple app on android studio, but constraints layout doesn't work correctly on real phone or virtual phone. I intent to put a button on the center of layout, and an edit text at top of layout, but when i run, both of it located same position at right-top layout, so i can't type a text and press the button.
I try to use RelativeLayout and it worked, so i guess the problem come from ConstraintLayout. Please help me fix it!

I have already install"ConstraintsLayout For Android 1.0.1 or lower", and "Solver For ConstraintsLayout 1.0.1 or lower". In build.gradle have added compile 'com.android.support.constraint:constraint-layout:1.0.1' I use Android Studio version 2.3. And here is my xml code:

<?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"
tools:context="my.android.myfirstapp.MainActivity">


<Button
    android:id="@+id/btn_jump"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Jump Activity"
    tools:layout_editor_absoluteX="128dp"
    tools:layout_editor_absoluteY="269dp" />

<EditText
    android:id="@+id/edt_Name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName"
    android:text=""
    tools:layout_editor_absoluteX="85dp"
    tools:layout_editor_absoluteY="62dp" />
</android.support.constraint.ConstraintLayout>

And here is my simple app when run:
enter image description here

View answer