{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
In previous article, we looked at Notification API with Hello SmartWatch demo. In this article, we will focus on Control API.
http://forum.xda-developers.com/smartwatch/sony/tut-introduction-smart-watch-t2807896
http://forum.xda-developers.com/smartwatch/sony/tut-smartwatch-app-development-part-2-t2807954
http://forum.xda-developers.com/smartwatch/sony/tut-smartwatch-app-development-part-3-t2807966
Control API is responsible for
Extension lifecycle: It allows you to start and stop extension using Intent. Extension means SmartWatch Host application.
Control.Intents.CONTROL_START_INTENT
Control.Intents.CONTROL_STOP_INTENT.
Controlling the display: Normally we don't require to control the display. Default screen state is "Auto", for the specific need you can change screen state by using Intent.
Control.Intents.SCREEN_STATE_OFF
Control.Intents.SCREEN_STATE_AUTO
Control.Intents.SCREEN_STATE_DIM
Control.Intents.SCREEN_STATE_ON
Controlling the LEDs: It used to switch on /off LEDs based on notification.
Control.Intents.CONTROL_LED_INTENT
Controlling the vibrator: It allows you to vibrate SmartWatch.
Control.Intents.CONTROL_VIBRATE_INTENT
Key event: It is used to capture hardware key i.e. home, back and menu key, which is available in SmartWatch2.
Control.Intents.CONTROL_KEY_EVENT_INTENT
Touch event: It is used to capture touch events.
Control.Intents.CONTROL_TOUCH_EVENT_INTENT
Control.Intents.CONTROL_SWIPE_EVENT_INTENT
Control.Intents.CONTROL_OBJECT_CLICK_EVENT_INTENT
Sony's Add-on SDK version 2.0 supports ListView and GridView but this article focuses on basic controls only. For the demo I will create a simple layout with ImageView and TextView. I will animate ImageView with thread and also capture onClick event of ImageView.
Screen Shots
Open Accessory emulator and select SmartWatch 2
Select Control API
Select Hello SmartWatch Extension
Enjoy dancing android
Click on Android will fire onClick event from host app to extension app
Click on menu hardware button to make menu item visible.
Step 1: Create java class named "HelloControlSmartWatch2.java" and extend with ControlExtension.
Code:
package com.kpbird.hellosmartwatch;
import android.content.Context;
import android.location.Address;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import com.sonyericsson.extras.liveware.aef.control.Control;
import com.sonyericsson.extras.liveware.extension.util.control.ControlExtension;
import com.sonyericsson.extras.liveware.extension.util.control.ControlObjectClickEvent;
import com.sonyericsson.extras.liveware.extension.util.control.ControlTouchEvent;
import com.sonyericsson.extras.liveware.extension.util.control.ControlView;
import com.sonyericsson.extras.liveware.extension.util.control.ControlView.OnClickListener;
import com.sonyericsson.extras.liveware.extension.util.control.ControlViewGroup;
public class HelloControlSmartWatch2 extends ControlExtension {
private static final int ANIMATION_DELTA_MS = 500;
private static final int MENU_ITEM_0 = 0;
private static final int MENU_ITEM_1 = 1;
private static final int MENU_ITEM_2 = 2;
private boolean mIsShowingAnimation = false;
private Animation mAnimation = null;
private Handler mHandler;
private ControlViewGroup mLayout = null;
private String TAG = this.getClass().getSimpleName();
private Bundle[] mMenuItemsText = new Bundle[3];
public HelloControlSmartWatch2(Context context, String hostAppPackageName,Handler handler) {
super(context, hostAppPackageName);
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
mHandler = handler;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.hello_control_2, null);
mLayout = parseLayout(layout);
if(mLayout !=null){
ControlView androidAnim = mLayout.findViewById(R.id.imgHelloControl);
androidAnim.setOnClickListener(new OnClickListener() {
@Override
public void onClick() {
Toast.makeText(mContext, "Button Clicked", Toast.LENGTH_LONG).show();
Log.i(TAG, "Android Button Clicked");
toggleAnimation();
}
});
}
mMenuItemsText[0] = new Bundle();
mMenuItemsText[0].putInt(Control.Intents.EXTRA_MENU_ITEM_ID, MENU_ITEM_0);
mMenuItemsText[0].putString(Control.Intents.EXTRA_MENU_ITEM_TEXT, "Item 1");
mMenuItemsText[1] = new Bundle();
mMenuItemsText[1].putInt(Control.Intents.EXTRA_MENU_ITEM_ID, MENU_ITEM_1);
mMenuItemsText[1].putString(Control.Intents.EXTRA_MENU_ITEM_TEXT, "Item 2");
mMenuItemsText[2] = new Bundle();
mMenuItemsText[2].putInt(Control.Intents.EXTRA_MENU_ITEM_ID, MENU_ITEM_2);
mMenuItemsText[2].putString(Control.Intents.EXTRA_MENU_ITEM_TEXT, "Item 3");
}
@Override
public void onResume() {
super.onResume();
showLayout(R.layout.hello_control_2, null);
startAnimation();
}
@Override
public void onPause() {
super.onPause();
stopAnimation();
}
@Override
public void onDestroy() {
stopAnimation();
mHandler = null;
};
public static int getSupportedControlWidth(Context context) {
return context.getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_width);
}
public static int getSupportedControlHeight(Context context) {
return context.getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_height);
}
@Override
public void onTouch(ControlTouchEvent event) {
Log.i(TAG, "onTouch() " + event.getAction());
}
@Override
public void onObjectClick(ControlObjectClickEvent event) {
Log.i(TAG, "onObjectClick() " + event.getClickType());
if (event.getLayoutReference() != -1) {
mLayout.onClick(event.getLayoutReference());
}
}
@Override
public void onKey(int action, int keyCode, long timeStamp) {
Log.i(TAG, "onKey() " + action + "\t" + keyCode + "\t" + timeStamp);
if (action == Control.Intents.KEY_ACTION_RELEASE
&& keyCode == Control.KeyCodes.KEYCODE_OPTIONS) {
showMenu(mMenuItemsText);
}
}
@Override
public void onMenuItemSelected(int menuItem) {
Log.d(TAG, "onMenuItemSelected() - menu item " + menuItem);
if (menuItem == MENU_ITEM_0) {
clearDisplay();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
onResume();
}
}, 1000);
}
}
private void toggleAnimation() {
if (mIsShowingAnimation) {
stopAnimation();
}
else {
startAnimation();
}
}
private void startAnimation() {
if (!mIsShowingAnimation) {
mIsShowingAnimation = true;
mAnimation = new Animation();
mAnimation.run();
}
}
private void stopAnimation() {
if (mIsShowingAnimation) {
// Stop animation on accessory
if (mAnimation != null) {
mAnimation.stop();
mHandler.removeCallbacks(mAnimation);
mAnimation = null;
}
mIsShowingAnimation = false;
}
}
private class Animation implements Runnable {
private int mIndex = 1;
private boolean mIsStopped = false;
Animation() {
mIndex = 1;
}
public void stop() {
mIsStopped = true;
}
@Override
public void run() {
int resourceId;
switch (mIndex) {
case 1:
resourceId = R.drawable.dancing_android_0;
break;
case 2:
resourceId = R.drawable.dancing_android_1;
break;
default:
Log.e(TAG, "mIndex out of bounds: " + mIndex);
resourceId = R.drawable.dancing_android_0;
break;
}
mIndex++;
if (mIndex > 2) {
mIndex = 1;
}
if (!mIsStopped) {
updateAnimation(resourceId);
}
if (mHandler != null && !mIsStopped) {
mHandler.postDelayed(this, ANIMATION_DELTA_MS);
}
}
private void updateAnimation(int resourceId) {
sendImage(R.id.imgHelloControl, resourceId);
}
};
}
Step 2: Open HelloExtensionService.java and override "createExtensionControl" method. In this method we need to identify accessory type before creating object of HelloControlSmartWatch2 class. To identify accessory type ExtensionUtils class has method named "DeviceInfoHealper".
Code:
@Override
public ControlExtension createControlExtension(String hostAppPackageName) {
// First we check if the API level and screen size required for
// SampleControlSmartWatch2 is supported
boolean advancedFeaturesSupported = DeviceInfoHelper.isSmartWatch2ApiAndScreenDetected(this, hostAppPackageName);
if (advancedFeaturesSupported) {
return new HelloControlSmartWatch2(this,hostAppPackageName, new Handler());
} else {
return null;
}
}
Step 3: Open HelloRegistrationInformation.java and change return value from 0 to 2 of "getRequiredControlApiVersion" method, 0 means our example doesn't require Control API, 1 and 2 represent minimum version of API required. We also need to override method named "isDisplaySizeSupported" for the confirmation of Display Size.
Code:
...
...
@Override
public int getRequiredControlApiVersion() {
return 2;
}
....
@Override
public boolean isDisplaySizeSupported(int width, int height) {
return ((width == HelloControlSmartWatch2.getSupportedControlWidth(mContext)
&& height == HelloControlSmartWatch2
.getSupportedControlHeight(mContext) || width == HelloControlSmartWatch2
.getSupportedControlWidth(mContext) && height == HelloControlSmartWatch2
.getSupportedControlHeight(mContext)) );
}
...
...
Step 4: Finally, Open AndroidManiFest.xml and add following action in HelloExtensionReceiver. It will require to capture onClick, onTouch and onObject click event.
Code:
...
...
<action android:name="com.sonyericsson.extras.aef.control.TOUCH_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.SWIPE_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.OBJECT_CLICK_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.MENU_ITEM_SELECTED" />
...
...
Step 5: Compile & Execute HelloSmartWatch example
Download Source CodeNote: 1. Import project in eclipse 2. Make sure that you change SmartExtensionUtils and SmartExtensionAPI path from project properties.
Related
I'm building a complete build of Android with tropo: (Google tropo)
Here's my tropo hosted script in javascript:
Code:
if (typeof number == 'undefined') {//IF the call doesn't come from me (there's no variable set)
var callerId=currentCall.callerID;
var textmessage=currentCall.initialText
hangup()
call('(Put your phone number Here', {network: 'SMS'});
//Analyse message and format it for sending
var message = new Array();
var nbMessages=((textmessage.length())/149) ;//.length() ????? why????
var i=0;
for(i=0;i<nbMessages;i++){
message[i]=callerId+textmessage.substr(i*149,149);
say(message[i]);
wait(1000);
}
hangup()
}
else //SENDING PART:number and text are parameters
{
call(number, {network:"SMS"});
say(text);
}
I've used the CM9 source code for the galaxy s2 that I downloaded and builded following this guide: (Google teamhacksung CyanogenMod9 How to build)
For sending, I simply post an HTTP Post request to my tropo app
Here's the code
I modified the SMSManager.java class in android.telephony package
Code:
public void sendTextMessage(
String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent) {
if (TextUtils.isEmpty(destinationAddress)) {
throw new IllegalArgumentException("Invalid destinationAddress");
}
if (TextUtils.isEmpty(text)) {
throw new IllegalArgumentException("Invalid message body");
}
/* OLD METHOD FOR SMS BY CARRIER
try {
ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
if (iccISms != null) {
iccISms.sendText(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
}
} catch (RemoteException ex) {
// ignore it
}*/
//My new Method via tropo
//Création de l'objet Tropo SMS
TropoSms sms = new TropoSms(destinationAddress, text, sentIntent,deliveryIntent);
sms.send();
}
/**/
public void sendMultipartTextMessage(
String destinationAddress, String scAddress, ArrayList<String> parts,
ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents) {
if (TextUtils.isEmpty(destinationAddress)) {
throw new IllegalArgumentException("Invalid destinationAddress");
}
if (parts == null || parts.size() < 1) {
throw new IllegalArgumentException("Invalid message body");
}
if (parts.size() > 1) {
/*//OLD METHOD FOR SMS CARRIER
try {
ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
if (iccISms != null) {
iccISms.sendMultipartText(destinationAddress, scAddress, parts,
sentIntents, deliveryIntents);
}
} catch (RemoteException ex) {
// ignore it
}*/
//My tropo Method
for(int i=0; i< parts.size();i++){
TropoSms sms = new TropoSms(destinationAddress, parts.get(i), sentIntents.get(i),deliveryIntents.get(i));
sms.send();
}
} else {
PendingIntent sentIntent = null;
PendingIntent deliveryIntent = null;
if (sentIntents != null && sentIntents.size() > 0) {
sentIntent = sentIntents.get(0);
}
if (deliveryIntents != null && deliveryIntents.size() > 0) {
deliveryIntent = deliveryIntents.get(0);
}
sendTextMessage(destinationAddress, scAddress, parts.get(0),
sentIntent, deliveryIntent);
}
}
Here I created the Tropo SMS class in the android.telephony.tropo package
Code:
/**
*
*/
package android.telephony.tropo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.telephony.SmsManager;
/**
* @author kevmegforest
*
*/
public class TropoSms {
protected String destinationAddress="Undefined";
protected String message="Undefined";
protected PendingIntent sentIntent;
protected PendingIntent deliveryIntent;
private static String token="1...4c";
public TropoSms(){
}
public TropoSms(String sendAddress, String text, PendingIntent sendIntent, PendingIntent deliverIntent){
destinationAddress=sendAddress;
message=text;
sentIntent=sendIntent;
deliveryIntent=deliverIntent;
}
/**------------------------------------------
* SETTERS AND GETTERS
* @return
*/
public String getDestinationAddress() {
return destinationAddress;
}
public String getMessage() {
return message;
}
//--------------------------------------------------
/**
* Methods
*/
public void send(){ //Success return true //Fail return false
boolean success=true;
this.message=manageText();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
HttpPost post = new HttpPost("https://api.tropo.com/1.0/sessions");
//Creating JSON object
JSONObject json= new JSONObject();
try {
json.put("token", token);
json.put("number", this.destinationAddress );
json.put("text", this.message);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
}
try {
StringEntity se = new StringEntity(json.toString());
post.setEntity(se);
//Post headers Setup
post.addHeader("accept", "application/json");
post.addHeader("content-type","application/json");
response=client.execute(post);
//Checking response
//HOW TO
if(response.getStatusLine().getStatusCode() !=200)
success=false;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success =false;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
}
this.manageIntent(success);
client.getConnectionManager().shutdown();//Ending connection
}
private void manageIntent(boolean sendsuccess)
{
if(sendsuccess)
{
try {
this.sentIntent.send(Activity.RESULT_OK);
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
this.sentIntent.send(SmsManager.RESULT_ERROR_GENERIC_FAILURE);
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String manageText()
{
String correctedText=this.message;//The last character in each table is the one to replace with
char characterToReplaceA[]={'à','â','ä','a'};
char characterToReplaceC[]={'ç','c'};
char characterToReplaceE[]={'é','è','ê','ë','e'};
char characterToReplaceI[]={'ì','î','ï','i'};
char characterToReplaceO[]={'ò','ô','ö','o'};
char characterToReplaceU[]={'ù','û','ü','u'};
char characterToReplace[][]={characterToReplaceA,characterToReplaceC,characterToReplaceE,characterToReplaceI,characterToReplaceO,characterToReplaceU};
for(int i=0;i<characterToReplace.length;i++){
for(int j=0;j<(characterToReplace[i].length-1);j++){
correctedText=correctedText.replace(characterToReplace[i][j],characterToReplace[i][characterToReplace[i].length-1]);
correctedText=correctedText.replace(Character.toUpperCase(characterToReplace[i][j]),Character.toUpperCase(characterToReplace[i][characterToReplace[i].length-1]));
}
}
return correctedText;
}
}
The sending part works really well. Since it's an API change I can use any SMS App in android and it would work.
But I have a problem with receiving.
My tropo script can only modify the body message of the sms. So when someone send a SMS message to tropo, I prefixed the body message with 10 characters representing it's phone number like this:
original message: "Hello"
new message:"15551231234Hello"
I then send this message to my phone
The modified class SubmitPdu in android.telephony package in the SMSMessage.java file
It's wherethe SMS app get the sms with the createfrompdu() method
Code:
public static SmsMessage createFromPdu(byte[] pdu, String format) {
SmsMessageBase wrappedMessage;
if (FORMAT_3GPP2.equals(format)) {
wrappedMessage = com.android.internal.telephony.cdma.SmsMessage.createFromPdu(pdu);
} else if (FORMAT_3GPP.equals(format)) {
wrappedMessage = com.android.internal.telephony.gsm.SmsMessage.createFromPdu(pdu);
} else {
Log.e(LOG_TAG, "createFromPdu(): unsupported message format " + format);
return null;
}
//Verify here if it comes from TROPO
Log.d("SMSNumberCompare", "Original number:"+wrappedMessage.getOriginatingAddress());
Log.d("SMSNumberCompare", "Tropo number:"+TropoSmsReceiver.TROPO_APP_PHONE_NUMBER);
if(PhoneNumberUtils.compare(wrappedMessage.getOriginatingAddress(), TropoSmsReceiver.TROPO_APP_PHONE_NUMBER)){
Log.d("SMSNumberCompare", "Comparison:"+(PhoneNumberUtils.compare(wrappedMessage.getOriginatingAddress(), TropoSmsReceiver.TROPO_APP_PHONE_NUMBER)));
//Creating TropoReceive Object
TropoSmsReceiver tropo = (TropoSmsReceiver) wrappedMessage; //Downcasting
tropo.formatFromTropo();
//upcasting
wrappedMessage=tropo;
}
return new SmsMessage(wrappedMessage);
}
And here's my TropoSmsReceiver Class which extends the SmsMessageBase class
Code:
package com.android.internal.telephony.tropo;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage.MessageClass;
import android.util.Log;
import com.android.internal.telephony.SmsMessageBase;
public class TropoSmsReceiver extends SmsMessageBase {
public final static String TROPO_APP_PHONE_NUMBER="###########";
//My new Methods
//this method will format the text to get the parameters transferred from the tropo text
public void formatFromTropo(){
Log.d("TropoFormat", "old address"+this.originatingAddress.address);
this.originatingAddress.address=PhoneNumberUtils.formatNumber(this.messageBody.substring(0, 10), PhoneNumberUtils.FORMAT_NANP );
Log.d("TropoFormat", "new address"+this.originatingAddress.address);
this.messageBody=this.messageBody.substring(11);
Log.d("TropoFormat", "new Body"+this.messageBody);
}
@Override
public MessageClass getMessageClass() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getProtocolIdentifier() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isReplace() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isCphsMwiMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMWIClearMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMWISetMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMwiDontStore() {
// TODO Auto-generated method stub
return false;
}
@Override
public int getStatus() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isStatusReportMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isReplyPathPresent() {
// TODO Auto-generated method stub
return false;
}
}
The interesting part is my new method formatFromTropo()
But I have a problem, it doesn't work.
It builds sucessfully
In the logcat, the debug log says it goes in the if statement (it says Comparison: true and it's placement is in the if)
But when the tropo.formatFromTropo() is called the catlog has no mention of any log declared in the TropoSmsReceiver File. How is that possible? Can you help me?
It's my first android project (app or android Source change) and java project so you can give me many recommendations(and comments) too.
Thank you
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();
}
}
I have a Slideshow for the Home Page of my app looks sorta like the Houzz apps Home Page, were it displays a new image daily. But their is one issue I am having is that all of my images are coming in so blurry. I've checked the Resolution and it shouldn't be that blurry for no reason at all. I've tried changing setScaleType such as switching it too CENTER, CENTER_CROP, and Etc... None of those seemed to work. I have tried everything too my knowledge and now I am stuck, Below are some of my relevant source code in order too successfully help me out on this issue.
This is the Home.java this is linked/runs functions of homebck.xml:
Code:
public class Home extends Fragment {
private final int FileUpload = 100;
public static final String URL =
private Context context;
private ImageView m_imageInformation;
private ImageView m_imageSave;
private ImageView m_imageWallPaper;
private ViewPager m_viewPager;
private ImageAdapter m_imageAdapter;
private ArrayList<ImageView> m_imageViewList;
private int[] m_galleryImages = new int[]{
R.drawable.ic_share,
R.drawable.ic_share,
R.drawable.ic_share
};
public static String popup_status = "";
public static File path = new File(Environment.getExternalStorageDirectory() + "");
public static Item[] fileList;
public static String chosenFile;
public static Boolean firstLvl = true;
ListAdapter adapter;
public static ArrayList<String> str = new ArrayList<String>();
public String dbPath = "/data/data/com.Celebration/";
private AboutPopup m_aboutPopup;
private InformationPopup m_informationPopup;
public static String ss;
public static List<DBManager.ImageModel> m_images;
public ImageLoader imageLoader;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
// super.onCreateView(inflater, container, savedInstanceState);
context = getActivity();
View rootView = inflater.inflate(R.layout.homebck, container, false);
m_viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
m_imageInformation = (ImageView) rootView.findViewById(R.id.image_information);
m_imageSave = (ImageView) rootView.findViewById(R.id.image_save);
m_imageWallPaper = (ImageView) rootView.findViewById(R.id.image_wallpaper);
initView();
m_imageInformation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Globals.imageNumber = m_viewPager.getCurrentItem();
m_informationPopup.showAtLocation(m_viewPager, 0, 0);
}
});
m_imageSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFileList();
onCreateDialog(100);
}
});
m_imageWallPaper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//sendIntent.setAction(Intent.ACTION_CHOOSER);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "");
sendIntent.putExtra(Intent.EXTRA_EMAIL, "");
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hello, I wanted to invite you to join this app with me! It's a guide about Celebration, FL. Come see ");
sendIntent.setType("text/plain");
//Sipdroid.this.startActivity(sendIntent);*/
context.startActivity(Intent.createChooser(sendIntent, "Tell a friend via..."));
}
});
return rootView;
}
public void initView(){
m_imageViewList = new ArrayList<ImageView>();
m_aboutPopup = new AboutPopup(getActivity());
m_informationPopup = new InformationPopup(getActivity());
Globals.m_dbMan = new DBManager(context);
m_images = Globals.m_dbMan.getImageListData();
m_imageViewList.clear();
if(m_images != null){
for (int i = m_images.size() - 1 ; i >= 0; i--) {
ImageView imageView = new ImageView(context);
setImage(imageView, i);
m_imageViewList.add(imageView);
}
}else{
ImageView imageView = new ImageView(context);
imageLoader = new ImageLoader(context);
imageLoader.DisplayImage(URL, imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
m_imageViewList.add(imageView);
}
m_imageAdapter = new ImageAdapter(m_imageViewList);
m_viewPager.setAdapter(m_imageAdapter);
}
public void setImage(ImageView m_imgView, int currentIndex)
{
File imgFile = new File(m_images.get(currentIndex).imagePath);
//Uri uri = Uri.fromFile(new File(lstImage.get(currentIndex).imagePath));
Bitmap myBitmap = decodeFile(imgFile);
m_imgView.setImageBitmap(myBitmap);
m_imgView.setAdjustViewBounds(true);
m_imgView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
public static Bitmap decodeFile(File f){
Bitmap b = null;
int IMAGE_MAX_SIZE = 1000;
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
int maxwh = Math.max(o.outWidth,o.outHeight);
while(maxwh / scale > IMAGE_MAX_SIZE)
scale *= 2;
}
Log.d("twinklestar.containerrecog", "width: " + o.outWidth + "height: " + o.outHeight + "scale:" + scale);
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
/* @Override
public void onClick(View v) {
Log.d("onclick", "ok");
switch (v.getId()){
case R.id.image_information:
{
Toast.makeText(context, "ok", Toast.LENGTH_SHORT).show();
break;
}
case R.id.image_save:
{
// loadFileList();
onCreateDialog(100);
break;
}
case R.id.image_wallpaper:
{
((Activity)context).finish();
break;
}
default:
break;
}
}*/
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
if (fileList == null) {
Log.e("TAG", "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case FileUpload:
builder.setTitle("Select a Folder to save");
builder.setPositiveButton("download", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
ImageView image = new ImageView(context);
imageLoader = new ImageLoader(context);
Globals.downloadFlag = true;
Globals.downlaodForSaving = true;
Globals.saveFolder = path.toString();
imageLoader.DisplayImage(URL, image);
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
dialog.dismiss();
onCreateDialog(FileUpload);
Log.d("TAG", path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
//UploadFragment.this.getActivity().removeDialog(DIALOG_LOAD_FILE);
dialog.dismiss();
onCreateDialog(FileUpload);
//UploadFragment.this.getActivity().showDialog(DIALOG_LOAD_FILE);
Log.d("TAG", path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
//Toast.makeText(UploadFragment.this.getActivity(), chosenFile, Toast.LENGTH_SHORT).show();
ss = path.getAbsolutePath() + "/" + chosenFile;
String extension = chosenFile.substring(chosenFile.indexOf(".") + 1);
if (extension.equals("png") || extension.equals("jpg") || extension.equals("bmp")) {
dialog.dismiss();
m_aboutPopup.showAtLocation(m_viewPager, 0, 0);
// onUpload(ss,chosenFile);
} else
Toast.makeText(getActivity(), "This is not image file!", Toast.LENGTH_SHORT).show();
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
Below this a SNIPPET/part of the MainActivity.java *hint URL1,2,3,4... Grabs the URL that is put into String:
Code:
public static String des;
public String myurl = null;
public class AboutPopup implements View.OnClickListener {
public View parent;
public PopupWindow popupWindow;
public ListView m_listHolder;
public EditText m_editDescription;
public Button m_btnUpload;
public DatePicker dp;
public TimePicker tp;
private PendingIntent pendingIntent;
private Spinner spinner;
private ImageView imageView;
private TextView selectImageurl;
private TextView imageDescription;
public AboutPopup(Context paramContext) {
this.parent = ((LayoutInflater) paramContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.settting_popup, null);
//this.parent.findViewBy)
this.popupWindow = new PopupWindow(this.parent, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, true);
this.m_editDescription = (EditText) parent.findViewById(R.id.setting_description);
this.m_btnUpload = (Button) parent.findViewById(R.id.btn_setting_show);
m_btnUpload.setOnClickListener(this);
selectImageurl = (TextView) parent.findViewById(R.id.select_imageurl);
imageDescription = (TextView) parent.findViewById(R.id.image_description);
selectImageurl.setTextSize(convertFromDp(24));
imageDescription.setTextSize(convertFromDp(24));
dp = (DatePicker) parent.findViewById(R.id.datePicker);
tp = (TimePicker) parent.findViewById(R.id.timePicker);
dp.setCalendarViewShown(false);
imageView = (ImageView)parent.findViewById(R.id.setting_image);
spinner = (Spinner) parent.findViewById(R.id.setting_spinner);
String[] platforms = paramContext.getResources(). getStringArray(R.array.dev_platforms);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(paramContext, R.layout.spinner_item, platforms);
spinner.setAdapter(adapter);
// If you want to continue on that TimeDateActivity
// If you want to go to new activity that code you can also write here
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
myurl = URL;
break;
case 1:
myurl = URL1;
break;
case 2:
myurl = URL3;
break;
case 3:
myurl = URL4;
break;
case 4:
break;
}
if(myurl != null){
imageLoader = new ImageLoader(MainActivity.this);
imageLoader.DisplayImage(myurl, imageView);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void showAtLocation(View pView, int left, int top) {
this.popupWindow.setOutsideTouchable(true);
this.popupWindow.setTouchable(true);
this.popupWindow.update();
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setAnimationStyle(R.style.PopupAnimation);
popupWindow.setWidth((int) (pView.getWidth() * 0.95));
popupWindow.setHeight((int) (pView.getHeight()));
popupWindow.showAtLocation(pView, Gravity.CENTER_VERTICAL, 0, 0);
// this.popupWindow.showAtLocation(pView, Gravity.CENTER, left, top);
}
public void hide() {
this.popupWindow.dismiss();
}
public boolean isVisible() {
return this.popupWindow.isShowing();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_setting_show: {
imageLoader = new ImageLoader(MainActivity.this);
Globals.downloadFlag = true;
imageLoader.DisplayImage(myurl, imageView);
ss = path.getAbsolutePath() + "/" + ImageLoader.fname;
des = this.m_editDescription.getText().toString();
Globals.alarmFileName[Globals.alarmNumber] = ImageLoader.fname;
Globals.alarmDescription[Globals.alarmNumber] = des;
Globals.alarmNumber = Globals.alarmNumber + 1;
String strDateTime = dp.getYear() + "-" + (dp.getMonth() + 1) + "-" + dp.getDayOfMonth();
Intent Intent = new Intent(MainActivity.this, AlarmReceiver.class);
Intent.putExtra("id",Globals.alarmNumber-1);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, Intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(),tp.getCurrentHour(), tp.getCurrentMinute());
Calendar current = Calendar.getInstance();
if(current.get(Calendar.YEAR) > cal.get(Calendar.YEAR) && current.get(Calendar.MONTH) > cal.get(Calendar.MONTH) && current.get(Calendar.DATE) > cal.get(Calendar.DATE)){
Toast.makeText(MainActivity.this, "Please select other time", Toast.LENGTH_SHORT).show();
return;
}
// schedule for every 30 seconds
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
if (des == null) {
Toast.makeText(MainActivity.this, "Input description in..", Toast.LENGTH_SHORT).show();
return;
} else {
popupWindow.dismiss();
}
}
break;
}
}
}
homebck.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="..."
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/homefragment"
android:background="@color/white">
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1">
<ImageView
android:id="@+id/image_information"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_information"
android:layout_weight="1" />
<ImageView
android:id="@+id/image_save"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_save"
android:layout_weight="1"
/>
<ImageView
android:id="@+id/image_wallpaper"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_share"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
Code:
public class ThreeFragment extends Fragment {
public View ThreeFragmentView = null;
public static TextView internalMemoryInfo;
public static Button IntBtn;
public ThreeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (ThreeFragmentView == null) ThreeFragmentView = inflater.inflate(R.layout.fragment_three, container, false);
internalMemoryInfo = (TextView) ThreeFragmentView.findViewById(R.id.textViewInternalMemoryInfo);
IntBtn = (Button) ThreeFragmentView.findViewById(R.id.InternalBtn);
return ThreeFragmentView;
}
public static void showText(String text) {
internalMemoryInfo.setText(text);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
registerForContextMenu(IntBtn);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
switch (v.getId()){
case R.id.InternalBtn:
menu.setHeaderTitle("Internal Memory Menu");
menu.add(0, ClearCacheMet, 0, "Clear Cache");
menu.add(0, Common, 0, "Go to Common Tab");
menu.add(0, ITEM_CANCEL, 0, "Cancel");
break;
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ClearCacheMet:
ClearCache(); <-------This not working
break;
case Common:
tabLayout.getTabAt(0).select(); <-------This working
break;
case ITEM_CANCEL:
ins.closeContextMenu(); <-------This working
break;
}
return true;
}
public static boolean deleteDir(File dir){
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static void ClearCache() {
File cache = ins.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
}
}
}
try{
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
((ActivityManager) ins.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();
} else {*/
File externalcache = ins.getExternalCacheDir();
File externalappDir = new File(externalcache.getParent());
if (externalappDir.exists()) {
String[] children = externalappDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(externalappDir, s));
}
}
} else {
Log.d(TAG, "No externalappDir");
}
/*}*/
} catch (Exception e) {
Log.d(TAG, "MainActivity in ClearCache");
}
}
I have fragment(ThreeFragment) with button(InternalBtn) that have a context menu. Context menu registered with registerForContextMenu(IntBtn); Menu item ClearCacheMet not working. I cannot see neither Toast.makeText().show(); nor Log.d(TAG, "ClearCache"); Common and ITEM_CANCEL items working. I cannot understand why? Please help me.
Toast.makeText(getActivity(), "Called !", Toast.LENGTH_SHORT).show(); not called in ClearCache() function. ClearCacheMet and Common were initialized in other fragment.
public class OneFragment extends Fragment {
public View OneFragmentView = null;
public static final int Common = 25;
public static final int ClearCacheMet = 50;
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);
}
}
}