I'm still in the proccess of creating my app. I'm trying to make it to where when i click the imabe button it will go to a new activity. each image button has it's on activity.
code*
`
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main);
val open: ImageButton = findViewById<ImageButton>(R.id.card1)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, TMs::class.java)
startActivity(intent)
})
val open: ImageButton = findViewById<ImageButton>(R.id.card2)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, Schematics::class.java)
startActivity(intent)
})
val open: ImageButton = findViewById<ImageButton>(R.id.card3)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, PartsCheatSheets::class.java)
startActivity(intent)
})
val open: ImageButton = findViewById<ImageButton>(R.id.card4)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, GeneratorLoadWiring::class.java)
startActivity(intent)
})
val open: ImageButton =findViewById<ImageButton>(R.id.card5)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, Hdt::class.java)
startActivity(intent)
})
val open: ImageButton =findViewById<ImageButton>(R.id.card6)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, GCP::class.java)
startActivity(intent)
})
val open: ImageButton =findViewById<ImageButton>(R.id.card7)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, SP::class.java)
startActivity(intent)
})
val open: ImageButton =findViewById<ImageButton>(R.id.card8)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, Cummins::class.java)
startActivity(intent)
})
}
}`
when its set up like this it works but only when i click the first one then go to the second one and so on down the list.
code*
`
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main);
val open: ImageButton = findViewById<ImageButton>(R.id.card1)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, TMs::class.java)
startActivity(intent)
val open: ImageButton = findViewById<ImageButton>(R.id.card2)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, Schematics::class.java)
startActivity(intent)
val open: ImageButton = findViewById<ImageButton>(R.id.card3)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, PartsCheatSheets::class.java)
startActivity(intent)
val open: ImageButton = findViewById<ImageButton>(R.id.card4)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, GeneratorLoadWiring::class.java)
startActivity(intent)
val open: ImageButton =findViewById<ImageButton>(R.id.card5)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity,Hdt::class.java)
startActivity(intent)
val open: ImageButton =findViewById<ImageButton>(R.id.card6)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity,GCP::class.java)
startActivity(intent)
val open: ImageButton =findViewById<ImageButton>(R.id.card7)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity,SP::class.java)
startActivity(intent)
val open: ImageButton =findViewById<ImageButton>(R.id.card8)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity,Cummins::class.java)
startActivity(intent)
})
})
})
})
})
})
})
})
}
}`
Change:
val open: ImageButton = findViewById<ImageButton>(R.id.card1)
open.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, TMs::class.java)
startActivity(intent)
})
To:
val card1: ImageButton = findViewById<ImageButton>(R.id.card1)
card1.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, TMs::class.java)
startActivity(intent)
})
And do like this for the other buttons as well
Do it like
val open1: ImageButton = findViewById<ImageButton>(R.id.card1)
val open2: ImageButton = findViewById<ImageButton>(R.id.card2)
val open3: ImageButton = findViewById<ImageButton>(R.id.card3)
val open4: ImageButton = findViewById<ImageButton>(R.id.card4)
val open5: ImageButton =findViewById<ImageButton>(R.id.card5)
val open6: ImageButton =findViewById<ImageButton>(R.id.card6)
val open7: ImageButton =findViewById<ImageButton>(R.id.card7)
val open8: ImageButton =findViewById<ImageButton>(R.id.card8)
open1.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, TMs::class.java)
startActivity(intent)
})
open1.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, Schematics::class.java)
startActivity(intent)
})
open2.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, PartsCheatSheets::class.java)
startActivity(intent)
})
open3.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, GeneratorLoadWiring::class.java)
startActivity(intent)
})
open4.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, Hdt::class.java)
startActivity(intent)
})
open5.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, GCP::class.java)
startActivity(intent)
})
open6.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, SP::class.java)
startActivity(intent)
})
open7.setOnClickListener(View.OnClickListener {
val intent = Intent(this#MainActivity, Cummins::class.java)
startActivity(intent)
})
Related
I am getting an error everytime I submit my post without an image, submission of the image is optional because I run an if condition before appending the imagePath. working on a MEAN stack up to which I am new in.
mime-type-validator
import { AbstractControl } from "#angular/forms";
import { Observable, Observer, of } from "rxjs";
export const mimeType = (
control: AbstractControl
): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> => {
if (typeof(control.value) === 'string') {
return of(null);
}
const file = control.value as File;
const fileReader = new FileReader();
const frObs = Observable.create(
(observer: Observer<{ [key: string]: any }>) => {
fileReader.addEventListener("loadend", () => {
const arr = new Uint8Array(fileReader.result as ArrayBuffer).subarray(0, 4);
let header = "";
let isValid = false;
for (let i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
switch (header) {
case "89504e47":
isValid = true;
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
case "ffd8ffe3":
case "ffd8ffe8":
isValid = true;
break;
default:
isValid = false; // Or you can use the blob.type as fallback
break;
}
if (isValid) {
observer.next(null);
} else {
observer.next({ invalidMimeType: true });
}
observer.complete();
});
fileReader.readAsArrayBuffer(file);
}
);
return frObs;
};
create-post-component
import { Component, Inject, Input, OnInit} from '#angular/core';
import { ActivatedRoute, ParamMap } from '#angular/router';
import { FormControl, FormGroup, Validators } from '#angular/forms'
import { PostModel } from 'src/app/Models/post.model';
import { PostsService } from 'src/app/Services/posts.service';
import { Router } from '#angular/router'
import { mimeType } from 'src/app/auth/Validators/mime-type.validator'
import Swal from 'sweetalert2';
#Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent {
public mode = 'user';
private postId : string;
public post: PostModel;
isLoading : boolean = false;
imagePreview: string;
PostForm = new FormGroup({
title: new FormControl('', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]),
content: new FormControl('', [Validators.required, Validators.minLength(1)]),
image: new FormControl(null, {validators:[], asyncValidators: [mimeType] })
})
constructor(public postsService: PostsService, public route: ActivatedRoute, private router: Router){
}
ngOnInit(){
this.route.paramMap.subscribe((paramMap: ParamMap)=>{
if(paramMap.has('postId')){
this.mode = 'edit';
this.postId = paramMap.get('postId');
this.isLoading = true;
this.postsService.getPost(this.postId).subscribe(postdata =>{
this.isLoading = false;
this.post = {id: postdata._id, title: postdata.title, content: postdata.content , imagePath: postdata.imagePath};
this.PostForm.setValue({ title: this.post.title, content: this.post.content, image: this.post.imagePath });
});
}
else{
this.mode = 'user';
this.postId = null;
}
})
}
onAddPost()
{
if(this.PostForm.invalid){
return;
}
this.isLoading = true;
if (this.mode === 'user'){
this.postsService.addPosts(this.PostForm.value.title, this.PostForm.value.content, this.PostForm.value.image)
this.isLoading = false;
Swal.fire({
position: 'center',
icon: 'success',
title: 'Post added!',
showConfirmButton: false,
timer: 2000
})
}
else{
this.postsService.updatePosts(
this.postId,
this.PostForm.value.title,
this.PostForm.value.content,
this.PostForm.value.image
);
this.router.navigateByUrl('/user');
}
this.PostForm.reset();
}
onImagePicked(event: Event){
const file = (event.target as HTMLInputElement).files[0];
this.PostForm.patchValue({image: file});
this.PostForm.get('image').updateValueAndValidity();
const reader = new FileReader();
reader.onload = () => {
this.imagePreview = reader.result as string;
};
reader.readAsDataURL(file);
}
}
posts-service.ts
import { Injectable } from '#angular/core';
import { PostModel } from '../Models/post.model';
import { HttpClient } from '#angular/common/http'
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators'
#Injectable(
{ providedIn: 'root' }
)
export class PostsService {
constructor(private http: HttpClient) { }
private posts: PostModel[] = [];
private postsUpdated = new Subject<PostModel[]>()
getPosts() {
this.http.get<{ message: string, posts: any }>('http://localhost:3300/api/posts')
.pipe(
map((postData) => {
return postData.posts.map(post => {
return {
title: post.title,
content: post.content,
id: post._id,
imagePath: post.imagePath
}
})
}))
.subscribe(transformedPosts => {
this.posts = transformedPosts;
this.postsUpdated.next([...this.posts]) //updating the posts so that it is available to the rest of the app
})
}
getUpdatedPostsListener() {
return this.postsUpdated.asObservable()
}
getPost(id: string) {
// return {...this.posts.find( p => p.id === id)} //p implies each post, and p.id implies that post's id
return this.http.get<{ _id: string; title: string; content: string, imagePath: string }>("http://localhost:3300/api/posts/" + id);
}
addPosts(title: string, content: string, image: File) {
const postData = new FormData();
postData.append('title', title);
postData.append('content', content);
if(image != undefined){
postData.append('image', image, title);
}
this.http.post<{ message: string, post: PostModel }>('http://localhost:3300/api/posts', postData).subscribe((responseData) => {
const post: PostModel = { id: responseData.post.id, title: title, content: content, imagePath: responseData.post.imagePath }
this.posts.push(post);
this.postsUpdated.next([...this.posts]);
})
}
updatePosts(id: string, title: string, content: string, image: File | string) {
let postData: PostModel | FormData;
if (typeof image === "object") {
postData = new FormData();
postData.append("id", id);
postData.append("title", title);
postData.append("content", content);
if(image != undefined){
postData.append("image", image, title);
}
} else {
postData = {
id: id,
title: title,
content: content,
imagePath: image
};
}
this.http
.put("http://localhost:3300/api/posts/" + id, postData)
.subscribe(response => {
const updatedPosts = [...this.posts];
const oldPostIndex = updatedPosts.findIndex(p => p.id === id);
const post: PostModel = {
id: id,
title: title,
content: content,
imagePath: ""
};
updatedPosts[oldPostIndex] = post;
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
// this.router.navigate(["/"]);
});
}
deletePosts(postId: string) {
this.http.delete('http://localhost:3300/api/posts/' + postId)
.subscribe(() => {
const updatedPosts = this.posts.filter(post => post.id !== postId);
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
})
}
}
I am developing an app with Flutter and Firebase.
I want to store the _id with SharedPreferences permanently.
Therefore, i looked after it, but my code doesnt work at all.
It always throws the error:
type 'Future' is not a subtype of type 'String'
Here is my code:
class Profile with ChangeNotifier {
String _id;
void setName(String name) {
const url =
'myurl';
http
.post(url, body: json.encode({'name': name, 'description': name}))
.then((response) {
_id = json.decode(response.body)['name'];
});
addID();
}
Future<void> updateName(String name, String id) async {
String url =
'myurl';
await http.patch(url,
body: json.encode({'name': 'Ein Titel', 'description': name}));
}
And here are my methods with the SharedPrefs:
String getID() {
return getIDOffline();
}
addID() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('id', _id);
}
getIDOffline() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
String stringValue = prefs.getString('id');
return stringValue;
}
Try this:
void setName(String name) {
const url = 'myurl';
var body = json.encode({'name': name, 'description': name});
var response = await http.post(url, body: body);
String id = json.decode(response.body)['name'];
addID(id);
}
addID(id) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('id', id);
}
Future<String> getID() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
String stringValue = prefs.getString('id');
return stringValue;
}
Your getID is async function so it return Future and not String..
I have a subclass Employee and a Base class Person.
In the constructor of the Person class, I call the setter function that sets the attributes after some validation.
But in the setter function I cannot get the properties of Employee Class.
//Employee.ts
import Person from "./Person"
class Employee extends Person {
empID: string = '';
designation: string = '';
constructor (props) {
super(props);
}
}
let obj = {empID:123,designation:"developer",firstName:"John",lastName:"Doe"}
let employee: Employee = new Employee(obj)
//Person.ts
export default class Person {
firstName: string = '';
lastName: string = '';
constructor (props:object) {
this.props = props
}
set props(props:object) {
console.log("this",this)
/***************prints Employee { firstName: '', lastName: '' } cannot access empID and designation **********/
for (const f in props) {
if (this.hasOwnProperty(f)) {
this[f] = props[f]
}
}
}
}
But this works
//Employee.ts
import Person from "./Person"
class Employee extends Person {
empID: string = '';
designation: string = '';
constructor () {
super();
}
}
let obj = {empID:123,designation:"developer",firstName:"John",lastName:"Doe"}
let employee: Employee = new Employee()
employee.props = obj
//Person.ts
export default class Person {
firstName: string = '';
lastName: string = '';
constructor () {
}
set props(props:object) {
console.log("this",this)
/***************prints Employee { firstName: '', lastName: '', empID: '', designation: '' } **********/
for (const f in props) {
if (this.hasOwnProperty(f)) {
this[f] = props[f]
}
}
}
}
Am I doing something wrong in the first example.
Thanks in advance.
When you call super the subclass is not initialized yet. You can set props right after super call:
constructor (props) {
super();
this.props = props;
}
Playground
I am trying to build a bot. So in one Node.js file, I am getting the following error while using ActivityHandler-
TypeError: Class extends value undefined is not a constructor or null
Here is the code which I am using -
const { ActivityHandler } = require('botbuilder');
const { LuisRecognizer, QnAMaker } = require('botbuilder-ai');
class DispatchBot extends ActivityHandler {
constructor(logger) {
super();
if (!logger) {
logger = console;
logger.log('[DispatchBot]: logger not passed in, defaulting to console');
}
const dispatchRecognizer = new LuisRecognizer({
applicationId: process.env.LuisAppId,
endpointKey: process.env.LuisAPIKey,
endpoint: `https://${ process.env.LuisAPIHostName }.api.cognitive.microsoft.com`
}, {
includeAllIntents: true,
includeInstanceData: true
}, true);
const qnaMaker = new QnAMaker({
knowledgeBaseId: process.env.QnAKnowledgebaseId,
endpointKey: process.env.QnAAuthKey,
host: process.env.QnAEndpointHostName
});
this.logger = logger;
this.dispatchRecognizer = dispatchRecognizer;
this.qnaMaker = qnaMaker;
this.onMessage(async (context, next) => {
this.logger.log('Processing Message Activity.');
const recognizerResult = await dispatchRecognizer.recognize(context);
const intent = LuisRecognizer.topIntent(recognizerResult);
await this.dispatchToTopIntentAsync(context, intent, recognizerResult);
await next();
});
this.onMembersAdded(async (context, next) => {
const welcomeText = 'Type a greeting or a question about the weather to get started.';
const membersAdded = context.activity.membersAdded;
for (let member of membersAdded) {
if (member.id !== context.activity.recipient.id) {
await context.sendActivity(`Welcome to Dispatch bot ${ member.name }. ${ welcomeText }`);
}
}
await next();
});
}
async dispatchToTopIntentAsync(context, intent, recognizerResult) {
switch (intent) {
case 'l_luis':
await this.processLuis(context, recognizerResult.luisResult);
break;
case 'q_sample-qna':
await this.processSampleQnA(context);
break;
default:
this.logger.log(`Dispatch unrecognized intent: ${ intent }.`);
await context.sendActivity(`Dispatch unrecognized intent: ${ intent }.`);
break;
}
}
}
module.exports.DispatchBot = DispatchBot;
Error -
class DispatchBot extends ActivityHandler {
^
TypeError: Class extends value undefined is not a constructor or null
So what is the way to avoid this kind of problem?
My problem got solved by just uninstalling botbuilder package and reinstalling it.
I'm trying to record audio via the microphone in the browser and then save it to file server side using Node and a binary server. I am using this tutorial as a guide but am having trouble getting it to work with Angular2. Currently it appears to be saving some type of file to the server but it's not any type of playable audio. Here's all my code:
import { Component } from '#angular/core';
import { ContributorService } from './contributor.service';
import { CardDetailService } from './card-detail.service';
import { CardDetailComponent } from './card-detail.component';
import { Router, ActivatedRoute, Params } from '#angular/router';
import { Location } from '#angular/common';
declare let navigator: any;
declare let MediaRecorder: any;
declare let BinaryClient: any;
#Component({
selector: 'contributor',
template: `
<h1>Record Message</h1>
<button (click)='start()'>Start</button>
<button (click)='stop()'>Stop</button>
<button (click)='play()'>Play</button>
<a>{{hf}}</a>
<button class="go-back" (click)="goBack()">Done</button>
`
})
export class ContributorComponent {
private chunks: any[] = [];
private recorder;
private audio;
private counter = 1;
private Stream;
private recording = false;
constructor(
private contributorService: ContributorService,
private cardDetailService: CardDetailService,
private location: Location,
private route: ActivatedRoute,
private router: Router,
) {}
ngOnInit() {
let client = new BinaryClient('ws://localhost:9001');
client.on('open', function() {
let Stream = client.createStream();
});
let audio = {
tag: 'audio',
type: 'audio/ogg',
ext: '.ogg',
gUM: {audio: true}
};
let context = new AudioContext();
if (!navigator.getUserMedia) {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
}
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true }, this.success, function(e) {
alert('Error capturing audio.');
});
} else {
alert('getUserMedia not supported in this browser.');
}
}
start() {
this.recording = true;
}
stop() {
this.recording = false;
this.Stream.end();
}
recorderProcess(e) {
let left = e.inputBuffer.getChannelData(0);
this.Stream.write(this.convertFloat32ToInt16(left));
}
success(e) {
let context = new AudioContext();
// the sample rate is in context.sampleRate
let audioInput = context.createMediaStreamSource(e);
let recorder = context.createScriptProcessor(2048, 1, 1);
this.recorder.onaudioprocess = function(e){
if (!this.recording) { return; };
console.log ('recording');
var left = e.inputBuffer.getChannelData(0);
this.Stream.write(this.convertoFloat32ToInt16(left));
};
audioInput.connect(this.recorder);
this.recorder.connect(context.destination);
}
convertFloat32ToInt16(buffer) {
let l = buffer.length;
let buf = new Int16Array(l);
while (l--) {
buf[l] = Math.min(1, buffer[l]) * 0x7FFF;
}
return buf.buffer;
}
goBack() {
this.location.back();
}
}
and here are the errors it throws:
contributor.component.ts:96Uncaught TypeError: Cannot read property 'recorder' of undefined(…)ContributorComponent.success # contributor.component.ts:96
core.umd.js:3004 EXCEPTION: Error in ./ContributorComponent class ContributorComponent - inline template:4:10 caused by: Cannot read property 'end' of undefinedErrorHandler.handleError