я уже с ума схожу где то = не так стоит, хееелп
DatabaseHelper
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DB_NAME = "rasp.sqlite";
private static final int SCHEMA = 1; // версия базы данных
static final String TABLE = "myrasp";
private static String DB_PATH;
public SQLiteDatabase getDb() {
return database;
}
public static final String COLUMN_ID = "id";
public static final String COLUMN_CLASS = "class";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_UROKID = "urok_id";
public static final String COLUMN_UROK = "urok";
// public static final String COLUMN_DO = "do";
// public static final String COLUMN_STATION = "station";
public SQLiteDatabase database;
private Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, SCHEMA);
this.myContext = context;
//DB_PATH = "/data/data/student.wsiz.rzeszow.pl.myapplication/databases/";
DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();
///DB_NAME = databaseName;
openDataBase();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
public void create_db() {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();//Создает и/или открывает базу данных
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database!");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
String path = DB_PATH + DB_NAME;
try {
checkDb = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
//Андроид не любит утечки ресурсов, все должно закрываться
if (checkDb != null) checkDb.close();
return checkDb != null;
}
/**
* метод проверки наличия в БД таблицы
*/
public boolean checkTableInDB(String TABLE) {
boolean result = false;
Cursor cur = database.query("sqlite_master", new String[]{ " name " } , " type = ? AND name = ? " , new String[]{ " table " , TABLE}, null, null, null);
cur.moveToLast();
if (cur.getCount() > 0) result = true;
cur.close();
return result;
}
/**
* метод проверки наличия поля в таблице
*/
public boolean checkFieldInTable(String nameTable, String nameField) {
boolean result = false;
try {
Cursor cur = database.rawQuery("PRAGMA table_info('" + nameTable + "')", null);
cur.moveToFirst();
while (!cur.isAfterLast()) {
String name = " ";
try {
name = cur.getString(cur.getColumnIndexOrThrow("name"));
} catch (IllegalArgumentException e) {
}
if (name.equals(nameField)) {
result = true;
break;
}
cur.moveToNext();
}
cur.close();
cur = null;
} catch (SQLException e) {
}
return result;
}
private void copyDataBase() throws IOException {
// Открываем поток для чтения из уже созданной нами БД источник в assets
InputStream externalDbStream = myContext.getAssets().open(DB_NAME);
// Путь к уже созданной пустой базе в андроиде
String outFileName = DB_PATH + DB_NAME;
// Теперь создадим поток для записи в эту БД побайтно
OutputStream localDbStream = new FileOutputStream(outFileName);
// Собственно, копирование
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
// Мы будем хорошими мальчиками (девочками) и закроем потоки
localDbStream.close();
externalDbStream.close();
}
// @Override
// public void onCreate(SQLiteDatabase db) {
/**
* Метод получения всех данных из таблицы
*/
public Cursor getAllData(String dbTable) {
return database.query(dbTable, null, null, null, null, null, null);
}
/**
* Метод получения данных из таблицы по условию
*/
// public Cursor getDataByWhere(String table, String[] columns, String where, String[] where_args) {
// return database.query(table, columns, where, where_args, null, null, null);
// }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/** public void create_db() {
InputStream myInput = null;
OutputStream myOutput = null;
try {
File file = new File(DB_PATH + DB_NAME);
if (!file.exists()) {
this.getReadableDatabase();
myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
} catch (IOException ex) {
}
}**/
/**
* Метод открытия БД
*/
public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (database == null) {
create_db();
database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
}
return database;
}
// public void open() throws SQLException {
// String path = DB_PATH + DB_NAME;
// database = SQLiteDatabase.openDatabase(path, null,
// SQLiteDatabase.OPEN_READONLY);
// }
@Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}
}
Main2Activity
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
String classID, tabID;Bundle b;
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
Bundle bundle = getIntent().getExtras();
classID = bundle.getString("classID");
toolbar.setTitle("Класс:" + classID);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
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();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main2, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position){
case 0:
BlankFragment1 bf1 = new BlankFragment1();
b = new Bundle();
b.putString("tabID","1");
return bf1;
case 1:
BlankFragment2 bf2 =new BlankFragment2();
b = new Bundle();
b.putString("tabID","2");
return bf2;
case 2:
BlankFragment3 bf3 = new BlankFragment3();
b = new Bundle();
b.putString("tabID","3");
return bf3;
case 3:
BlankFragment4 bf4 = new BlankFragment4();
b = new Bundle();
b.putString("tabID","4");
return bf4;
case 4:
BlankFragment5 bf5 = new BlankFragment5();
b = new Bundle();
b.putString("tabID","5");
return bf5;
case 5:
BlankFragment6 bf6 = new BlankFragment6();
b = new Bundle();
b.putString("tabID","5");
return bf6;
case 6:
BlankFragment7 bf7 = new BlankFragment7();
b = new Bundle();
b.putString("tabID","5");
return bf7;
default:
return null;
}
}
@Override
public int getCount() {
// Show 3 total pages.
return 7;
}
}}
Blank_fragment1
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
/**
* A simple {@link Fragment} subclass.
*/
public class BlankFragment1 extends ListFragment {
String classId;
SimpleCursorAdapter userAdapter;
DatabaseHelper sqlHelper;
Cursor userCursor;
ListView mList;
public BlankFragment1() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
super.onCreate(savedInstanceState);
View rootview = inflater.inflate(R.layout.fragment_blank_fragment1,container,false);
mList=(ListView) rootview.findViewById(android.R.id.list);
return rootview;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = getActivity().getIntent().getExtras();
classId = bundle.getString("classID");
sqlHelper = new DatabaseHelper(getActivity());
sqlHelper.create_db();
}
@Override
public void onResume() {
super.onResume();
try {
sqlHelper.openDataBase();
userCursor = sqlHelper.database.rawQuery("select * from " + DatabaseHelper.TABLE + " where class = " + classId + "and day = 1", null);
String[] headers = new String[]{DatabaseHelper.COLUMN_UROK};
userAdapter = new SimpleCursorAdapter(getActivity(), R.layout.item, userCursor, headers, new int[]{R.id.uroki}, 0);
mList.setAdapter(userAdapter);
}
catch (SQLException ex){}
}
}
Виртуальный выделенный сервер (VDS) становится отличным выбором
Возникла проблема, сейчас пользователи могут заполнить поле как цифрами так и не заполнять его вообще (заполнится автоматически текстом)
Всем привет,есть приложение с авторизацией в ВК,сохраняю данные в SharedPreferences при логине,и на второй активити пытаюсь их поймать:
Я хочу связать BottomNagation и NagationViewНо "Run" выдает следующее