[Q] Problem developing app for Android - General Questions and Answers

Hi All,
I am a not experienced developer. All I want to do is make a small app to track information of football on TV. I want to do it through a small DB however I've been struggling a lot with an error I've been trying to discover in the last two weeks but I have not been able.
I have teh following code in the class I create the DB
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_GDATE = "gdate";
public static final String KEY_GTIME = "gtime";
public static final String KEY_GGAME = "ggame";
public static final String KEY_GCOMPETITION = "gcompetition";
public static final String KEY_GCHANNEL = "gchannel";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "FonTV";
private static final String DATABASE_TABLE = "games";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table games (_id integer primary key autoincrement, "
+ "gdate text not null, gtime text not null, ggame text not null" +
"gcompetition text not null, gchannel text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(String gdate, String gtime, String ggame, String gcompetition, String gchannel )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_GDATE, gdate);
initialValues.put(KEY_GTIME, gtime);
initialValues.put(KEY_GGAME, ggame);
initialValues.put(KEY_GCOMPETITION, gcompetition);
initialValues.put(KEY_GCHANNEL, gchannel);
return db.insert(DATABASE_TABLE, null, initialValues);
}
}
And the main class where I try to insert data has this:
public class ResultsDBActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertContact("12/may", "08:00", "Leeds vs York", "JUME Cup", "ITV, BBC");
id = db.insertContact("13/may", "09:00", "London vs Bath", "JUME Cup", "ITV, BBC2");
db.close();
}
}
However when I try to run it, the debugger shows and error that says:
E/Database(330): android.database.sqlite.SQLiteException: no such table: games: , while compiling: INSERT INTO games(gchannel, ggame, gtime, gdate, gcompetition) VALUES(?, ?, ?, ?, ?);
I’ve trying to change parameters and many things but I haven’t found where the problem is. Can someone help me please?

Related

[Q] Audio Level Meter

Hello
I'm new to programming and I'm trying to make a java application that will "hear" (not record necessarily) the sound and display how loud is.I'm thinking of converting the sound recordings to numbers,so I can see the difference on the sound levels.I got this code and I added the "getLevel()" method,which returns the amplitude of the current recording,but it's returning -1 everytime.I guess I'm not using it properly. Any ideas how I must call this method?I have to deliver my project in a week,so any help will be much appreciated!
Code:
public class Capture extends JFrame {
protected boolean running;
ByteArrayOutputStream out;
public Capture() {
super("Capture Sound Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container content = getContentPane();
final JButton capture = new JButton("Capture");
final JButton stop = new JButton("Stop");
final JButton play = new JButton("Play");
capture.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(false);
ActionListener captureListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
capture.setEnabled(false);
stop.setEnabled(true);
play.setEnabled(false);
captureAudio();
}
};
capture.addActionListener(captureListener);
content.add(capture, BorderLayout.NORTH);
ActionListener stopListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
capture.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
running = false;
}
};
stop.addActionListener(stopListener);
content.add(stop, BorderLayout.CENTER);
ActionListener playListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
playAudio();
}
};
play.addActionListener(playListener);
content.add(play, BorderLayout.SOUTH);
}
private void captureAudio() {
try {
final AudioFormat format = getFormat();
DataLine.Info info = new DataLine.Info(
TargetDataLine.class, format);
final TargetDataLine line = (TargetDataLine)
AudioSystem.getLine(info);
line.open(format);
line.start();
Runnable runner = new Runnable() {
int bufferSize = (int)format.getSampleRate()
* format.getFrameSize();
byte buffer[] = new byte[bufferSize];
public void run() {
out = new ByteArrayOutputStream();
running = true;
try {
while (running) {
int count =
line.read(buffer, 0, buffer.length);
if (count > 0) {
out.write(buffer, 0, count);
System.out.println(line.getLevel()); // |-this is what i added-|
}
}
out.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-1);
}
}
};
Thread captureThread = new Thread(runner);
captureThread.start();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-2);
}
}
private void playAudio() {
try {
byte audio[] = out.toByteArray();
InputStream input =
new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais =
new AudioInputStream(input, format,
audio.length / format.getFrameSize());
DataLine.Info info = new DataLine.Info(
SourceDataLine.class, format);
final SourceDataLine line = (SourceDataLine)
AudioSystem.getLine(info);
line.open(format);
line.start();
Runnable runner = new Runnable() {
int bufferSize = (int) format.getSampleRate()
* format.getFrameSize();
byte buffer[] = new byte[bufferSize];
public void run() {
try {
int count;
while ((count = ais.read(
buffer, 0, buffer.length)) != -1) {
if (count > 0) {
line.write(buffer, 0, count);
}
}
line.drain();
line.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-3);
}
}
};
Thread playThread = new Thread(runner);
playThread.start();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-4);
}
}
private AudioFormat getFormat() {
float sampleRate = 8000;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = true;
return new AudioFormat(sampleRate,
sampleSizeInBits, channels, signed, bigEndian);
}
@SuppressWarnings("deprecation")
public static void main(String args[]) {
JFrame frame = new Capture();
frame.pack();
frame.show();
}
}
Ok,I managed to make it capture audio and print on a xls file the timestamp and the value of the current sample,but there is a problem : even I've put some spaces between the time and the value and it seems that they are in different columns,they are actualy on the same column of the xls,it's just expanded and covers the next column (I can put a print screen if you don't understand).How can I make it print the data of time and amplitude in two different columns?Here's my code of the class which creates the file and saves the data on xls :
Code:
package soundRecording;
import java.io.File;
import java.util.Formatter;
public class Save {
static Formatter y;
public static void createFile() {
Date thedate = new Date();
final String folder = thedate.curDate();
final String fileName = thedate.curTime();
try {
String name = "Time_"+fileName+".csv";
y = new Formatter(name);
File nof = new File(name);
nof.createNewFile();
System.out.println("A new file was created.");
}
catch(Exception e) {
System.out.println("There was an error.");
}
}
public void addValues(byte audio) {
Date d = new Date();
y.format("%s " + " %s%n",d.curTime(), audio);
}
public void closeFile() {
y.close();
}
}

[Completed] [Q] Save checkboxes to SQLite Database

I have 4 checboxes that i want to enter in the SQLite table. I want that the values of the checkboxes must only be saved if the checkbox's are ticked. This is the code that i have used. The checkboxes are getting saved to the database but all of them are getting saved, even the checbox's i didnt check. Please help me with the code
Code:
private void SaveContent() {
EditText IdInput = (EditText) findViewById(R.id.StationID);
EditText NameInput = (EditText) findViewById(R.id.StationName);
EditText EmailInput = (EditText) findViewById(R.id.Email);
EditText LocationInput = (EditText) findViewById(R.id.Location);
final CheckBox wifi = (CheckBox) findViewById(R.id.Wifi);
if (wifi.isChecked()) {
final String strWifi = wifi.getText().toString();
}
final CheckBox toilets = (CheckBox) findViewById(R.id.Toilets);
if (toilets.isChecked()) {
final String strToilets = wifi.getText().toString();
}
final CheckBox lifts = (CheckBox) findViewById(R.id.Lifts);
if (lifts.isChecked()) {
final String strLifts = lifts.getText().toString();
}
final CheckBox ramps = (CheckBox) findViewById(R.id.Ramps);
if (ramps.isChecked()) {
final String strRamps =ramps.getText().toString();
}
final String strWifi = wifi.getText().toString();
final String strToilets = toilets.getText().toString();
final String strRamps = ramps.getText().toString();
final String strLifts = lifts.getText().toString();
final String strStationID = IdInput.getText().toString();
final String strName = NameInput.getText().toString();
final String strEmail = EmailInput.getText().toString();
final String strLocation = LocationInput.getText().toString();
final String strStationType = StationType[position];
new AlertDialog.Builder(this)
.setTitle("Details entered")
.setMessage(
" Details entered:\n" + strStationID + "\n" + strName + "\n " + strStationType +
"\n" + strWifi + "\n" + strToilets + "\n" + strLifts + "\n" + strRamps + "\n" +
strLocation + "\n" + strEmail )
.setNeutralButton("Back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
saveStation(strStationID, strName, strStationType, strWifi,strToilets, strLifts, strRamps, strLocation, strEmail);
}
}).show();
}
public void saveStation(String StationID, String StationName, String StationType, String Wifi, String Toilets,
String Lifts, String Ramps, String Location, String Email) {
try {
dbHelper.insertStation(StationID,StationName,StationType,Wifi,Toilets,Lifts,Ramps,Location,Email);
new AlertDialog.Builder(AddStation.this)
.setTitle("\nStation Saved Successfully\n")
.setNeutralButton("View",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
viewStatiton();
}
}).show();
} catch (SQLiteException sqle) {
android.util.Log.w(this.getClass().getName(),
" Error saving to database");
new AlertDialog.Builder(AddStation.this)
.setTitle("Couldn't save details")
.setNeutralButton("Next",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// do nothing
}
}).show();
}
}
Code:
public class SQL extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "FacilitiesReview";
static final String TABLE_NAME="Stations";
static final String COL_StationID="StationID";
static final String COL_StationNAME="StationName";
static final String COL_StationType="StationType";
static final String COL_Wifi="Wifi";
static final String COL_Toilets="Toilets";
static final String COL_Lifts="Lifts";
static final String COL_Ramps="Ramps";
static final String COL_Email="Email";
static final String COL_Location="Location";
private SQLiteDatabase database;
public SQL(Context context) {
super(context, DATABASE_NAME, null, 1);
database = getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE StationTable (StationID INTEGER PRIMARY KEY, StationName TEXT, " +
"StationType TEXT, Wifi TEXT, Toilets TEXT, Lifts TEXT, Ramps Text, Location TEXT, Email TEXT );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.w(this.getClass().getName(),
DATABASE_NAME + " database upgrade to version " + newVersion + " old data lost");
db.execSQL("DROP TABLE IF EXISTS details");
onCreate(db);
}
public long insertStation(String StationID, String StationName, String StationType, String Wifi, String Toilets,
String Lifts, String Ramps, String Location, String Email) {
ContentValues rowValues = new ContentValues();
rowValues.put("StationID", StationID);
rowValues.put("StationName", StationName);
rowValues.put("StationType", StationType);
rowValues.put("Wifi", Wifi);
rowValues.put("Toilets", Toilets);
rowValues.put("Lifts", Lifts);
rowValues.put("Ramps", Ramps);
rowValues.put("Location", Location);
rowValues.put("Email", Email);
return database.insertOrThrow("Station", null, rowValues);
}
public long getNumberOfRecords() {
Cursor c = database.query("Station",null,null, null, null, null, null);
return c.getCount();
}
public Cursor getAllRecords() {
return database.query(TABLE_NAME, null, null, null, null, null,
COL_StationNAME);
}
public void deleteAllRecords() {
database.delete(TABLE_NAME, null, null);
}
}
Hi there,
I'm sorry but I can't find anything related to your question.
Please post that in the forum bellow for more answers from the experts:
> Android Development and Hacking > Android Q&A, Help & Troubleshooting
Also you can read about that here: IDEs, Libraries, & Programming Tools or App Development Forums
Good luck

[Completed] Android Studio Listview Needs To Be Visible

Hi guys I am new to developing i need help with some codes. Hope you guys can help.
I am using Sqlite database i need to create a list view that display the word from database so hope you guys can help me. here is my code above. ty
//Code
public class Ortho extends ActionBarActivity {
private final String TAG = "Ortho";
DatabaseHelper dbhelper;
TextView word;
TextView mean;
AutoCompleteTextView actv;
Cursor cursor;
Button search;
int flag = 0;
ListView ls;
ArrayList<String> dataword;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ortho);
ls = (ListView) findViewById(R.id.mainlist);
ls.setVisibility(View.VISIBLE);
//need code here
dbhelper = new DatabaseHelper(this);
try {
dbhelper.createDataBase();
} catch (IOException e) {
Log.e(TAG, "can't read/write file ");
Toast.makeText(this, "error loading data", Toast.LENGTH_SHORT).show();
}
dbhelper.openDataBase();
word = (TextView) findViewById(R.id.word);
mean = (TextView) findViewById(R.id.meaning);
String[] from = {"english_word"};
int[] to = {R.id.text};
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.singalline, null, from, to);
// This will provide the labels for the choices to be displayed in the AutoCompleteTextView
adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@override
public CharSequence convertToString(Cursor cursor) {
return cursor.getString(1);
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
@override
public Cursor runQuery(CharSequence constraint) {
cursor = null;
int count = constraint.length();
if (count >= 1) {
String constrains = constraint.toString();
cursor = dbhelper.queryr(constrains);
}
return cursor;
}
});
briza-jann23 said:
Hi guys I am new to developing i need help with some codes. Hope you guys can help.
I am using Sqlite database i need to create a list view that display the word from database so hope you guys can help me. here is my code above. ty
//Code
public class Ortho extends ActionBarActivity {
private final String TAG = "Ortho";
DatabaseHelper dbhelper;
TextView word;
TextView mean;
AutoCompleteTextView actv;
Cursor cursor;
Button search;
int flag = 0;
ListView ls;
ArrayList<String> dataword;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ortho);
ls = (ListView) findViewById(R.id.mainlist);
ls.setVisibility(View.VISIBLE);
//need code here
dbhelper = new DatabaseHelper(this);
try {
dbhelper.createDataBase();
} catch (IOException e) {
Log.e(TAG, "can't read/write file ");
Toast.makeText(this, "error loading data", Toast.LENGTH_SHORT).show();
}
dbhelper.openDataBase();
word = (TextView) findViewById(R.id.word);
mean = (TextView) findViewById(R.id.meaning);
String[] from = {"english_word"};
int[] to = {R.id.text};
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.singalline, null, from, to);
// This will provide the labels for the choices to be displayed in the AutoCompleteTextView
adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@override
public CharSequence convertToString(Cursor cursor) {
return cursor.getString(1);
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
@override
public Cursor runQuery(CharSequence constraint) {
cursor = null;
int count = constraint.length();
if (count >= 1) {
String constrains = constraint.toString();
cursor = dbhelper.queryr(constrains);
}
return cursor;
}
});
Click to expand...
Click to collapse
Hi, thank you for using XDA assist.
There is a general forum for android here http://forum.xda-developers.com/android/help where you can get better help and support if you try to ask over there.
Good luck.
You can also ask here http://forum.xda-developers.com/coding/java-android

Is RecyclerView refreshed when AlertDialog's positive button gets pressed

My MainActivity has a RecyclerView adapter, and data to this RecyclerView is added through a AlertDialog which passes the entered text to the MainActivity. The recycler view gets refreshed somehow when the positive button in the dialog is pressed even though I never call notifyItemInserted() or notifyDatasetChange() after passing the new input. I want to know how this happens, my guess is the recyclerview is somehow refreshed after the positive button is pressed in the dialog box.
Custom AlertDialog Code:
Code:
public class CustomDialog extends AppCompatDialogFragment {
OnNoteAddedListener onNoteAddedListener;
public interface OnNoteAddedListener {
public void onClick(String note);
}
public CustomDialog(OnNoteAddedListener onNoteAddedListener) {
this.onNoteAddedListener = onNoteAddedListener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogLayout = inflater.inflate(R.layout.dialog_box, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogLayout).setPositiveButton("Ok", new DialogInterface.OnClickListener() {@Override
public void onClick(DialogInterface dialog, int id) {
EditText addNote = dialogLayout.findViewById(R.id.note_text);
String note = addNote.getText().toString();
onNoteAddedListener.onClick(note);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CustomDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
Adapter code:
Code:
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
{
private static final String TAG = "RecyclerViewAdapter";
private List<String> notesList;
private Context mContext;
private SendPositionConnector sendPositionConnector;
public interface SendPositionConnector
{
public void sendPosition(int position);
}
public RecyclerViewAdapter(List<String> notesList, Context mContext)
{
this.notesList = notesList;
this.mContext = mContext;
this.sendPositionConnector = (MainActivity)mContext;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position)
{
Log.d(TAG, "onBindViewHandler: called");
viewHolder.noteContent.setText(notesList.get(position));
viewHolder.parentLayout.setOnLongClickListener(new View.OnLongClickListener(){
@Override
public boolean onLongClick(View view)
{
Log.d(TAG, "onLongClick: long clicked on");
sendPositionConnector.sendPosition(position);
return false;
}
});
}
@Override
public int getItemCount()
{
return notesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView noteContent;
RelativeLayout parentLayout;
ImageView bullet;
public ViewHolder(@NonNull View itemView)
{
super(itemView);
bullet = itemView.findViewById(R.id.bullet);
noteContent = itemView.findViewById(R.id.text_content);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
Main Activity:
Code:
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.SendPositionConnector
{
private static final String TAG = "MainActivity";
private List<String> notesList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private int position;
public AgentAsyncTask agentAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.my_recycler_view);
registerForContextMenu(recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
agentAsyncTask = new AgentAsyncTask(notesList, getApplicationContext(), true, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
adapter = new RecyclerViewAdapter(notesList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
});
agentAsyncTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.add_note:
showDialogBox(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStop()
{
super.onStop();
new AgentAsyncTask(notesList, getApplicationContext(), false, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
}
}).execute();
}
@Override
protected void onDestroy()
{
super.onDestroy();
}
private boolean showDialogBox(MenuItem menuItem)
{
AppCompatDialogFragment dialogFragment = new CustomDialog(new CustomDialog.OnNoteAddedListener(){
@Override
public void onClick(String note)
{
Log.d(TAG, "onClick: "+ note);
notesList.add(note);
}
});
dialogFragment.show(getSupportFragmentManager(),"Adding");
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case R.id.delete:
notesList.remove(position);
adapter.notifyItemRemoved(position);
adapter.notifyItemRangeChanged(position, notesList.size());
return true;
default:
return false;
}
}
@Override
public void sendPosition(int position)
{
this.position = position;
}
private static class AgentAsyncTask extends AsyncTask<Void, Void, List<String>>
{
private List<String> notesList;
private boolean flag;
OnRead onRead;
Context context;
AppDataBase dataBase;
private static final String TAG = "AgentAsyncTask";
public interface OnRead
{
public void onRead(List<String> notesList);
}
private AgentAsyncTask(List<String> notesList,Context context,boolean flag, OnRead onRead)
{
this.notesList = notesList;
this.onRead = onRead;
this.flag = flag;
this.context = context;
}
@Override
protected List<String> doInBackground(Void... params)
{
dataBase = Room.databaseBuilder(context, AppDataBase.class, "database-name").build();
if(!flag)
{
Gson gson = new Gson();
Type type = new TypeToken<List<String>>() {}.getType();
String json = gson.toJson(notesList, type);
Log.d(TAG, "doInBackground: "+json);
Notes notes = new Notes();
notes.setNoteContent(json);
notes.setUid(1);
dataBase.notesDao().insertNotes(notes);
return notesList;
}
else
{
Gson gson = new Gson();
String notesListContent = dataBase.notesDao().getNotes();
if(dataBase.notesDao().getCount() != 0)
{
notesList = gson.fromJson(notesListContent, new TypeToken<List<String>>()
{
}.getType());
}
else
{
return notesList;
}
return notesList;
}
}
@Override
protected void onPostExecute(List<String> notesList)
{
super.onPostExecute(notesList);
if(flag)
onRead.onRead(notesList);
}
}
}

Problem to update clockwidget

I have try to develop a clock widget for me and it works not correctly then when I use a other app I think the clock stopps to count I think the problem is when I switch the app. I hope you can help me.
HTML:
public class WidgetManager extends AppWidgetProvider {
[user=439709]@override[/user]
public void onUpdate(final Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
final Date date = new Date();
final RemoteViews remote = new RemoteViews(context.getPackageName(),R.layout.widgetlayout);
Intent openActivity = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, openActivity, 0);
remote.setOnClickPendingIntent(R.id.button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remote);
remote.setTextViewText(R.id.hour, getHour());
remote.setTextViewText(R.id.minute, getMinute());
remote.setTextViewText(R.id.date, getDate());
updateText(context, remote);
runUpdater(context, remote);
}
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
public void updateText(Context context, RemoteViews remoteViews){
ComponentName widgetcomp = new ComponentName(context, WidgetManager.class);
AppWidgetManager.getInstance(context).updateAppWidget(widgetcomp, remoteViews);
}
public void runUpdater(final Context context, final RemoteViews remote){
final Handler handler = new Handler();
final Date date = new Date();
handler.postDelayed(new Runnable() {
[user=439709]@override[/user]
public void run() {
remote.setTextViewText(R.id.hour, getHour());
remote.setTextViewText(R.id.minute, getMinute());
remote.setTextViewText(R.id.date, getDate());
updateText(context, remote);
handler.removeCallbacks(this);
runUpdater(context, remote);
}
}, 1000); //update every second
}
public String getHour(){
DateFormat dfTime = new SimpleDateFormat("HH");
String time = dfTime.format(Calendar.getInstance().getTime());
return time;
}
public String getMinute(){
DateFormat dfTime = new SimpleDateFormat("mm");
String time = dfTime.format(Calendar.getInstance().getTime());
return time;
}
public String getDate(){
DateFormat dfTime = new SimpleDateFormat("E, d MMMM");
String time = dfTime.format(Calendar.getInstance().getTime());
return time;
}
}

Categories

Resources