In Android, I have 2 activities. Mainactivity takes input from 2 edittext (USERNAME-PASSWORD) and writes them to file.json located in asset folder , Output activity has 2 textview , which will read the values (USERNAME-PASSWORD)from file.json and set the text to TextView. This is how far I tried.
MainActivity.java
package com.example.io;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{
private EditText et1,et2;
private Button b;
String e1,e2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
et1 = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
b = (Button) findViewById(R.id.b);
e1=et1.getText().toString().trim();
e2=et2.getText().toString().trim();
b.setOnClickListener(new View.OnClickListener()
{
BufferedReader reader = null;
DataOutputStream dos = null;
BufferedWriter writer = null;
#Override
public void onClick(View v)
{
//ObjectMapper mapper = new ObjectMapper();
try
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",et1);
jsonObject.put("password",et2);
String FILENAME = "file.json";
String string = jsonObject.toString();
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Intent intent = new Intent(MainActivity.this,Output.class);
startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
}
});
}
#Override
public void onBackPressed()
{
DrawerLayout drawer = (DrawerLayout) 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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_input)
{
// Handle the camera action
}
else if (id == R.id.nav_output)
{
Intent intent = new Intent(MainActivity.this,Output.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Output.java
package com.example.io;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import org.json.simple.parser.JSONParser;
public class Output extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{
private TextView tv1;
private TextView tv2;
String id,password;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tv1 = findViewById(R.id.tv1);
tv2 = findViewById(R.id.tv2);
String json = null;
try
{
/*JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(new FileReader("C:\\Users\\I\\Desktop\\IO\\app\\src\\main\\assets\\file.json"));
JSONObject jsonObject = jsonArray.getJSONObject(0);
Functions functions = new Functions();
Bundle bundle = functions.MakeBundleFromJSON(jsonObject);*/
/*InputStream is = Output.this.getAssets().open("file.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");*/
InputStream is = getAssets().open("file.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
System.out.println(json);
JSONObject obj = new JSONObject(json);
tv1.setText(obj.getString("id"));
tv2.setText(obj.getString("password"));
}
catch (Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
}
#Override
public void onBackPressed()
{
DrawerLayout drawer = (DrawerLayout) 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.output, 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(MenuItem item)
{
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_input)
{
// Handle the camera action
Intent intent = new Intent(Output.this,MainActivity.class);
startActivity(intent);
}
else if (id == R.id.nav_output)
{
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My problem is I can't see any output in Output activity.
here is log
If u need a closer look see here in git
You can store the data in Shared Preference from your activity and the data will still persists when your application is closed.
You can visit the below link to Android developers official website
Shared Preference
Hope it helps.
Related
I am new at android and i am making a dictionary app with youtube tutorials, android.com, stackoverflow etc. for trainig. Now i have an issue with main drawer. I am gonna try explain with pics.
https://i.imgur.com/s9EjAna.jpg
When i start the app, dictionary page opening, it's okey. when i click to bookmark, bookmark page opening it's okey too but when i at bookmark page and clicking dictionary link, the dictionary page doesn't open.
here my codes, i used same codes for bookmark and dictionary page.
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_bookmark){
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){
goToFragment(bookmarkFragment, false);
}
}
if (id == R.id.nav_dict){
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){
goToFragment(dictionaryFragment, false);
}
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
but i think (it's just a guess, i am not sure) the problem is this codes
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
my all MainActivity.java is here
package com.example.dict;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import androidx.annotation.RequiresApi;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.Menu;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
MenuItem menuSetting;
Toolbar toolbar;
DBHelper dbHelper;
DictionaryFragment dictionaryFragment;
BookmarkFragment bookmarkFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbHelper = new DBHelper(this);
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);
dictionaryFragment = new DictionaryFragment();
bookmarkFragment = BookmarkFragment.getInstance(dbHelper);
goToFragment(dictionaryFragment, true);
dictionaryFragment.setOnFragmentListener(new FragmentListener() {
#Override
public void onItemClick(String value) {
String id = Global.getState(MainActivity.this,"dict_type");
int dicType = id == null? R.id.eng_kh:Integer.valueOf(id);
goToFragment(DetailFragment.getNewInstance(value, dbHelper, dicType), false);
}
});
bookmarkFragment.setOnFragmentListener(new FragmentListener() {
#Override
public void onItemClick(String value) {
String id = Global.getState(MainActivity.this,"dict_type");
int dicType = id == null? R.id.eng_kh:Integer.valueOf(id);
goToFragment(DetailFragment.getNewInstance(value, dbHelper, dicType), false);
}
});
EditText edit_search = findViewById(R.id.edit_search);
edit_search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
dictionaryFragment.filterValue(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menuSetting = menu.findItem(R.id.action_settings);
String id = Global.getState(this,"dict_type");
if (id != null)
onOptionsItemSelected(menu.findItem(Integer.valueOf(id)));
else {
ArrayList<String> source =dbHelper.getWord(R.id.eng_kh);
dictionaryFragment.resetDatasource(source);
}
return true;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#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.eng_kh) {
Global.saveState(this, "dict_type", String.valueOf(id));
ArrayList<String> source = dbHelper.getWord(id);
dictionaryFragment.resetDatasource(source);
menuSetting.setIcon(getDrawable(R.drawable.ic_lang));
return true;
} else if (id==R.id.kh_eng){
Global.saveState(this, "dict_type", String.valueOf(id));
ArrayList<String> source = dbHelper.getWord(id);
dictionaryFragment.resetDatasource(source);
menuSetting.setIcon(getDrawable(R.drawable.ic_lang2));
return true;
} else if (id==R.id.kh_kh){
Global.saveState(this, "dict_type", String.valueOf(id));
ArrayList<String> source = dbHelper.getWord(id);
dictionaryFragment.resetDatasource(source);
menuSetting.setIcon(getDrawable(R.drawable.ic_lang3));
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_bookmark){
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){
goToFragment(bookmarkFragment, false);
}
}
if (id == R.id.nav_dict){
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){
goToFragment(dictionaryFragment, false);
}
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
void goToFragment(Fragment fragment, boolean isTop){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
if (!isTop)
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (activeFragment.equals(BookmarkFragment.class.getSimpleName())){
menuSetting.setVisible(false);
toolbar.findViewById(R.id.edit_search).setVisibility(View.GONE);
toolbar.setTitle("Bookmark");
}else {
menuSetting.setVisible(true);
toolbar.findViewById(R.id.edit_search).setVisibility(View.VISIBLE);
toolbar.setTitle("");
}
return true;
}
}
and my activity_main_drawer is here
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<item android:title="Network">
<menu>
<item
android:id="#+id/nav_dict"
android:icon="#drawable/ic_dict"
android:title="Dictionary"/>
<item
android:id="#+id/nav_bookmark"
android:icon="#drawable/ic_bookmark"
android:title="#string/menu_bookmark" />
<item
android:id="#+id/nav_rate"
android:icon="#drawable/ic_thumb"
android:title="#string/menu_rate" />
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
</menu>
</item>
<item android:title="Other">
<menu>
<item
android:id="#+id/nav_help"
android:icon="#drawable/ic_help"
android:title="#string/menu_help" />
<item
android:id="#+id/nav_about"
android:icon="#drawable/ic_info"
android:title="#string/menu_about" />
</menu>
</item>
</menu>
if you need any more code, i can paste here. Thanks.
Inside onNavigationItemSelected, on clicking of Dictionary you are checking BookmarkFragment. It should be DictionaryFragment
Updated Code
if (id == R.id.nav_dict){
String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
if (!activeFragment.equals(DictionaryFragment.class.getSimpleName())){
goToFragment(dictionaryFragment, false);
}
}
Hello friends i am using seekbarpefernce library "com.yokkomi:seekbar-preference:1.0 " in my project the problem is that when i try to get value from this seekbar its always give me default value which i set in getting value from sharedperfernce please help me how to get the seekbar value when its changed here is my code geting sharedperfe value inside speakout method please look below speakout method in my code!
library link here:https://github.com/ghkim3221/SeekBarPreference
My perfernce sacreen:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreference
android:defaultValue="false"
android:key="autospeak"
android:title="Auto Speak"
android:summary="Turn on/off auto verse read"/>
<com.yokkomi.commons.preference.seekbar.SeekBarPreference
android:defaultValue="11"
android:dialogTitle="Verse Reading Speed"
android:key="versespeed"
android:summary="Adjust verse reading speed"
android:title="Verse Speed"
app:explain="Drag it left or right"
app:maxValue="20"
app:padding="3"/>
<com.yokkomi.commons.preference.seekbar.SeekBarPreference
android:defaultValue="8"
android:dialogTitle="Voice Picth Settings"
android:key="voicepitch"
android:summary="Adjust verse reading pitch"
android:title="Voice Pitch"
app:explain="Drag it left or right"
app:maxValue="20"
app:padding="3"/>
<SwitchPreference
android:defaultValue="false"
android:key="switchmode"
android:title="Turn on Dark Mode"
android:summary="Reading in night mode"/>
package bible.swordof.God;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.yokkomi.commons.preference.seekbar.SeekBarPreference;
import java.util.ArrayList;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
public class ALLVERSE extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,TextToSpeech.OnInitListener {
private ListView mylistview;
private ArrayList<String>versenumber;
private ArrayList<String>verselist;
private ArrayList<String>id;
private ArrayList<String>refernce;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private int chapternumber;
private String bookname;
public int versepos;
private TextView booknametitle;
TextToSpeech textToSpeech;
private static SharedPreferences sharedPreferences;
int result;
private static final int MY_DATA_CHECK_CODE = 0;
private FullverseAdopter fullverseAdopter;
RelativeLayout linearLayout;
#Override
protected void onDestroy() {
if (textToSpeech!= null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allverse);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
booknametitle = findViewById(R.id.bookname);
linearLayout=findViewById(R.id.color);
final Intent mIntent = getIntent();
booknumber = mIntent.getIntExtra("Boooknumber", 0);
chapternumber = mIntent.getIntExtra("Chapternumber", 0);
bookname = mIntent.getStringExtra("Bookname");
versepos=mIntent.getIntExtra("versenumber",1);
SharedPreferences sharedPreferences=this.getSharedPreferences("DATA",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("versenumber",versepos);
editor.commit();
booknametitle.setText(bookname.toString() + " " + chapternumber);
setSupportActionBar(toolbar);
toolbar.setTitle("ALL VERSE");
textToSpeech=new TextToSpeech(this,this);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
mylistview = findViewById(R.id.mylistview);
BaseAdapter baseAdapter = new BaseAdopter(this, versenumber, id, verselist, refernce);
mylistview.setAdapter(baseAdapter);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(DefaultSettings.autospeak(ALLVERSE.this)){
speakOut(verselist.get(versepos-1));
}
//speak after 1000ms
}
}, 1000);
mylistview.setSelection(Integer.valueOf(versepos)-1);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void setData() {
versenumber=new ArrayList<>();
verselist=new ArrayList<>();
refernce=new ArrayList<>();
id=new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("SELECT id, v, t from t_kjv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
if(cursor!=null && cursor.getCount() > 0)
{ if (cursor.moveToFirst())
{
do {
id.add(cursor.getString(0));
versenumber.add(cursor.getString(1));
verselist.add(cursor.getString(2));
refernce.add(bookname+" "+chapternumber);
}
while (cursor.moveToNext());
}
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite)
{ Intent intent=new Intent(this,Favourite.class);
startActivity(intent);
} else if (id == R.id.setting) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// here is getingperfernces always return 11 which i set as default value
private void speakOut(String text) {
sharedPreferences=getSharedPreferences("versespeed",MODE_PRIVATE);
float speed=(float)sharedPreferences.getInt("versespeed",11)/50;
if(speed<0.1)speed=0.1f;
/* float pitch=(float)sharedPreferences.getInt("voicepitch",11)/50;
if(pitch<0.1)pitch=0.1f;
textToSpeech.setPitch(pitch);*/
textToSpeech.setSpeechRate(speed);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(this, ""+speed, Toast.LENGTH_SHORT).show();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
}
I'm the developer of SeekBarPreference.
The SeekBarPreference is currently inoperative and not maintained.
I'm really sorry, and you'd better find another library.
I am developing an Android Studio app using Java. My app allows a user to sign in and view custom markers on a map with custom markers. When a user click on a custom marker they get taken to another activity.
My problem is, When accessing this activity via the custom marker, the app does not load the images stored in firebase.
Any Suggestions on what the problem might be? Thanks.
map activity that deals with the markers:
mMap.setOnMarkerClickListener
(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if (marker.getTitle().equals("Mario's Italian"))
startActivity(new Intent(MapView.this,
ItalianMenu.class));
if (marker.getTitle().equals("Bamboo Tandoori"))
startActivity(new Intent(MapView.this,
IndianMenu.class));
if (marker.getTitle().equals("King Chinese
Takeaway"))
startActivity(new Intent(MapView.this,
ChineseMenu.class));
return false;
}
});
activity that opens up when a user clicks the marker:
package myapp.zerbu.partyloader;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import myapp.zerbu.partyloader.Common.Common;
import myapp.zerbu.partyloader.Interface.ItemClickListener;
import myapp.zerbu.partyloader.Model.Category;
import myapp.zerbu.partyloader.ViewHolder.MenuViewHolder;
public class ItalianMenu extends AppCompatActivity
implements
NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference category;
TextView txtName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Mario's Italian");
setSupportActionBar(toolbar);
//Init Firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
//Basket
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own
action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new
ActionBarDrawerToggle(
this, drawer, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Set Name for user
View headerView = navigationView.getHeaderView(0);
txtName =
(TextView)headerView.findViewById(R.id.txtName);
txtName.setText(Common.currentUser.getName());
//Load menu
recycler_menu = (RecyclerView)
findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
FirebaseRecyclerAdapter<Category, MenuViewHolder>
adapter = new FirebaseRecyclerAdapter<Category,
MenuViewHolder>(Category.class,
R.layout.activity_italian_menu, MenuViewHolder.class,
category) {
#Override
protected void populateViewHolder(MenuViewHolder
viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem = model;
viewHolder.setImageClickListener(new
ItemClickListener() {
#Override
public void onClick(View view, int position,
boolean isLongClick) {
Toast.makeText(ItalianMenu.this,
""+clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout)
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.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_restaurants) {
// Handle the camera action
} else if (id == R.id.nav_basket) {
} else if (id == R.id.nav_orders) {
} else if (id == R.id.nav_logout) {
}
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I have a textview in my xml and I want to change the text from an intent. I've tried it before in the same class but on another xml and it works there. But after changing the contentView it don't work anymore. I want to set the displayName.
package de.myapp.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class UserAreaActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
//setContentView(R.layout.nav_header_user_area);
//final TextView displayName = (TextView) findViewById(R.id.displayName);
//Intent intent = getIntent();
//String dpdisplayName = intent.getStringExtra("displayName");
//displayName.setText(dpdisplayName);
setContentView(R.layout.activity_user_area);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
XML:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Mr. Android"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:id="#+id/displayName" />
[UPDATED] Use like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
setContentView(R.layout.activity_user_area);
Intent intentMain = getIntent();
String dpdisplayName = intentMain.getStringExtra("displayName");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navdisplayName = (TextView) headerView.findViewById(R.id.displayName);
navdisplayName.setText(dpdisplayName);
}
At First Remove
Calling Multiple time
setContentView(R.layout.activity_user_area); // Remove from 2nd time
Final View
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Dont call setTitle(""); Here
setContentView(R.layout.nav_header_user_area);
final TextView displayName = (TextView) findViewById(R.id.displayName);
Intent intent = getIntent();
String dpdisplayName = intent.getStringExtra("displayName");
displayName.setText(dpdisplayName);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("");
//code goes on here
}
while setting setContentView() second time, you have eventually changes your attached view hierarchy tree. Your changes to textview will no longer be visible since its not even attached to the activity
So I am creating an app that I want the user to be able to decide if they want to use WiFi or 4G to fetch the data after logging in (I will make another question about implementing the decision later, unless anyone wants to add that here too). So currently I have a MainActivity.java that will be handling the logging in (which I have yet to implement) and I have a NavDrawerActivity.java for the Navigation Drawer. Now obviously once I do the "log in" it goes to the Nav Drawer. However, I want the user to be able to choose whether or not to use Wifi or Data before logging in as well as being able to choose once they log in. So I guess this is a two part question, how would you implement this as well as, is it a good idea to put that in the login screen? Or should I just default it to always use wifi unless they change it and if I detect WiFi isn't enabled, have them enable it?
MainActivity.java code
package com.example.jamessingleton.chffrapi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "USE_YOUR_OWN_API_KEY";
static final String API_URL = "https://api.fullcontact.com/v2/person.json?";
static final String ClientId= "";
static final String ClientSecret = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new RetrieveFeedTask().execute();
Intent intent = new Intent(context, NavDrawerActivity.class);
startActivity(intent);
}
});
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}
}
NavDrawerActivity.java code
package com.example.jamessingleton.chffrapi;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//.setAction("Action", null).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) 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.nav_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();
FragmentManager fragmentSettingsManager = getFragmentManager();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
fragmentSettingsManager.beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit();
setTitle(R.string.action_settings);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.GONE);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
setTitle(R.string.speed_graph);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).commit();
setTitle(R.string.drive_player);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ThirdFragment()).commit();
setTitle(R.string.google_maps);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_share) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Go Check Out All Driving Data in the Play Store!");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Let me know if there is anything else you guys need and thank you guys for all the help :)
Here is the WifivsDataDialog code
package com.example.jamessingleton.chffrapi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
/**
* Created by James Singleton on 8/9/2016.
*/
public class WifivsDataDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_box)
.setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
It's not entirely clear what you would like to achieve.
Is it mandatory to fetch the data? What if the user has both Wi-Fi and mobile network disabled on the device? What if they choose to use Wi-Fi, but have only mobile network enabled on the device?
I would create a Dialog at the start of the app that explains this stuff and let the user choose if they would like to allow fetching data on mobile network, or Wi-Fi only, with a "Do not show this dialog again" CheckBox.
If the user chooses with the CheckBox checked, then that will be the default behaviour on further launches (and can be changed in the Preferences/Settings).
You could show the Dialog from the onCreate() of your login Activity.
For example:
connection_dialog.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Would you like to allow fetching data on mobile network?"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No, allow Wi-Fi only"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:text="OK"/>
</LinearLayout>
ConnectionDialogFragment.java:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ConnectionDialogFragment extends DialogFragment {
public ConnectionDialogFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.connection_dialog, container, false);
// set up your View here
return view;
}
}
And in your Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// ...
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("show_dialog", true)) {
showDialog();
}
}
private void showDialog() {
ConnectionDialogFragment dialog = new ConnectionDialogFragment();
dialog.show(getSupportFragmentManager(), "connection_dialog");
}
Check out the developer's guide on Dialogs.
When the user has chosen whether they want to use Wi-Fi only, or allow mobile network also, you could check the available connection with something like this:
// this method will return either
// ConnectivityManager.TYPE_MOBILE
// or
// ConnectivityManager.TYPE_WIFI
// or -1 (if no connection is available)
private int checkAvailableConnectionType() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
int type = activeNetwork.getType();
if(activeNetwork.isConnected() && (type == ConnectivityManager.TYPE_MOBILE ||
type == ConnectivityManager.TYPE_WIFI)) {
return type;
}
return -1;
}
And do your stuff according to the user's choice and the currently active connection (advise the user to turn on Wi-Fi, for example).